package cn.com.libertymutual.sp.service.impl;

import java.io.FileInputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaBuilder.In;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.BeanUtilExt;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.util.DateUtil;
import cn.com.libertymutual.core.util.InsureUtils;
import cn.com.libertymutual.core.util.StringUtil;
import cn.com.libertymutual.core.util.enums.CoreServiceEnum;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.core.web.util.RequestUtils;
import cn.com.libertymutual.core.xml.XmlBinder;
import cn.com.libertymutual.sp.bean.SysOperationLog;
import cn.com.libertymutual.sp.bean.TbSpActivity;
import cn.com.libertymutual.sp.bean.TbSpAgreementNoConfig;
import cn.com.libertymutual.sp.bean.TbSpApplicant;
import cn.com.libertymutual.sp.bean.TbSpApprove;
import cn.com.libertymutual.sp.bean.TbSpBank;
import cn.com.libertymutual.sp.bean.TbSpCashDetail;
import cn.com.libertymutual.sp.bean.TbSpCashLog;
import cn.com.libertymutual.sp.bean.TbSpDrawLog;
import cn.com.libertymutual.sp.bean.TbSpFlow;
import cn.com.libertymutual.sp.bean.TbSpFlowDetail;
import cn.com.libertymutual.sp.bean.TbSpManualDetail;
import cn.com.libertymutual.sp.bean.TbSpOrder;
import cn.com.libertymutual.sp.bean.TbSpProduct;
import cn.com.libertymutual.sp.bean.TbSpSaleLog;
import cn.com.libertymutual.sp.bean.TbSpScore;
import cn.com.libertymutual.sp.bean.TbSpScoreConfig;
import cn.com.libertymutual.sp.bean.TbSpScoreLogIn;
import cn.com.libertymutual.sp.bean.TbSpScoreLogOut;
import cn.com.libertymutual.sp.bean.TbSpScoreManual;
import cn.com.libertymutual.sp.bean.TbSpStoreConfig;
import cn.com.libertymutual.sp.bean.TbSpUser;
import cn.com.libertymutual.sp.bean.TbSysHotarea;
import cn.com.libertymutual.sp.dao.ActivityDao;
import cn.com.libertymutual.sp.dao.AgreementNoConfigDao;
import cn.com.libertymutual.sp.dao.ApplicantDao;
import cn.com.libertymutual.sp.dao.ApproveDao;
import cn.com.libertymutual.sp.dao.BankDao;
import cn.com.libertymutual.sp.dao.CashDetailDao;
import cn.com.libertymutual.sp.dao.CashLogDao;
import cn.com.libertymutual.sp.dao.DrawLogDao;
import cn.com.libertymutual.sp.dao.FlowDao;
import cn.com.libertymutual.sp.dao.FlowDetailDao;
import cn.com.libertymutual.sp.dao.ManualDetailDao;
import cn.com.libertymutual.sp.dao.OperationLogDao;
import cn.com.libertymutual.sp.dao.OrderDao;
import cn.com.libertymutual.sp.dao.ProductConfigDao;
import cn.com.libertymutual.sp.dao.ProductDao;
import cn.com.libertymutual.sp.dao.ScoreConfigDao;
import cn.com.libertymutual.sp.dao.ScoreDao;
import cn.com.libertymutual.sp.dao.ScoreLogInDao;
import cn.com.libertymutual.sp.dao.ScoreLogOutDao;
import cn.com.libertymutual.sp.dao.ScoreManualDao;
import cn.com.libertymutual.sp.dao.SpSaleLogDao;
import cn.com.libertymutual.sp.dao.StoreConfigDao;
import cn.com.libertymutual.sp.dao.TbSysHotareaDao;
import cn.com.libertymutual.sp.dao.UserDao;
import cn.com.libertymutual.sp.dto.epayment.BatchQryWithPayOrderMsgContent;
import cn.com.libertymutual.sp.dto.epayment.Epayment;
import cn.com.libertymutual.sp.mq.MessageDto;
import cn.com.libertymutual.sp.mq.ResponseStatus;
import cn.com.libertymutual.sp.req.DrawReq;
import cn.com.libertymutual.sp.service.api.BranchSetService;
import cn.com.libertymutual.sp.service.api.ScoreService;
import cn.com.libertymutual.sys.bean.SysBranch;
import cn.com.libertymutual.sys.bean.SysServiceInfo;
import cn.com.libertymutual.sys.dao.ISysRoleUserDao;
import cn.com.libertymutual.sys.dao.SysBranchDao;

@Service("scoreService")
public class ScoreServiceImpl implements ScoreService {

	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private ScoreManualDao manualDao;
	@Autowired
	private ISysRoleUserDao roleUserDao;
	@Autowired
	private ScoreConfigDao scoreConfigDao;
	@Autowired
	private TbSysHotareaDao tbSysHotareaDao;
	@Resource
	private ScoreDao scoreDao;
	@Resource
	private RedisUtils redisUtils;
	@Autowired
	private ProductDao productDao;
	@Autowired
	private ManualDetailDao manualDetailDao;
	@Autowired
	private OperationLogDao operationLogDao;
	@Autowired
	private ProductConfigDao productConfigDao;
	@Autowired
	private ApproveDao approveDao;
	@Autowired
	private BranchSetService branchSetService;
	@Autowired
	private UserDao userDao;
	@Autowired
	private DrawLogDao drawLogDao;
	@Autowired
	private ActivityDao activityDao;
	@Autowired
	private ApplicantDao applicantDao;
	@Autowired
	private ScoreLogInDao scoreLogInDao;
	@Autowired
	private ScoreLogOutDao scoreLogOutDao;
	@Autowired
	private OrderDao orderDao;
	@Autowired
	private SysBranchDao sysBranchDao;
	@Autowired
	private LevelServiceImpl levelService;
	@Autowired
	private BankDao bankDao;
	@Autowired
	private SpSaleLogDao spSaleLogDao;
	@Autowired
	private CashLogDao cashLogDao;
	@Autowired
	private TbSysHotareaDao hotareaDao;
	@Autowired
	private CashDetailDao cashDetailDao;
	@Autowired
	private StoreConfigDao storeConfigDao;
	@Autowired
	private AgreementNoConfigDao agreementNoConfigDao;
	@Resource
	private RestTemplate restTemplate;
	@Autowired
	private FlowDetailDao flowDetailDao;
	@Autowired
	private FlowDao flowDao;

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult scoreByHand(String path, String remark, MultipartFile file) throws Exception {
		ServiceResult sr = new ServiceResult();
		TbSpFlow flow = flowDao.findByType(Constants.FLOW_MANUAL_SCORE);
		if (null == flow) {
			sr.setFail();
			sr.setResult("请先配置手工发放审批流！");
			return sr;
		}
		List<TbSpFlowDetail> details = flowDetailDao.findByFlowNo(flow.getFlowNo());
		if (CollectionUtils.isNotEmpty(details) && details.size() <= 1) {
			sr.setFail();
			sr.setResult("请先配置手工发放审批流！");
			return sr;
		}
		log.info("-----------path--------{}", path);
		FileInputStream is = new FileInputStream(path);
		String userId = Current.userInfo.get().getUserId();
		// InputStream is = file.getInputStream();
		ClassLoader classloader = org.apache.poi.poifs.filesystem.POIFSFileSystem.class.getClassLoader();
		URL res = classloader.getResource("org/apache/poi/poifs/filesystem/POIFSFileSystem.class");
		String dpath = res.getPath();
		System.out.println("Core POI came from " + dpath);
		// 获取工作表
		Workbook workbook = WorkbookFactory.create(is);

		log.info("-----------workbook--------{}", workbook);
		int sheetNumber = workbook.getNumberOfSheets();
		log.info("sheetNumber-----{}", sheetNumber);
		Sheet sheet = null;
		Row row = null;
		List<TbSpUser> ulist = null;
		int totalRows = 0;
		Double totalScore = 0.0;
		Integer manualId = null;
		for (int nowsheet = 0; nowsheet < sheetNumber; nowsheet++) {
			log.info("-----------校验sheetNumber--------{}", sheetNumber);
			// Excel工作表
			sheet = workbook.getSheetAt(nowsheet);
			log.info("-----------行数--------{}", sheet.getPhysicalNumberOfRows());
			// 校验表格正确性
			String reg = "^(\\-|\\+)?\\d+(\\.\\d+)?$";

			if (!"客户手机号".equals(sheet.getRow(0).getCell(0).toString())
					|| !"发放数量".equals(sheet.getRow(0).getCell(1).toString())) {
				sr.setFail();
				sr.setResult("表格格式有误，请仔细检查！");
				return sr;
			}
			// Excel工作表总行数
			totalRows += sheet.getPhysicalNumberOfRows();
			log.info("totalRows-------{}", totalRows);
			log.info("totalgetLastRowNum-------{}", sheet.getLastRowNum());
			// 校验电话号码
			for (int r = 1; r < totalRows; r++) {
				row = sheet.getRow(r);
				if (null == row) {
					continue;
				}
				if (row.getCell(0).getCellType() != Cell.CELL_TYPE_BLANK
						&& row.getCell(1).getCellType() != Cell.CELL_TYPE_BLANK) {
					ulist = userDao.findByMobile(String.valueOf(row.getCell(0)));
					if (null == ulist || ulist.size() == 0) {
						sr.setFail();
						sr.setResult("第" + (r + 1) + "行电话不存在，请仔细检查！");
						return sr;
					}
					log.info("---2---{}", Pattern.compile(reg).matcher(row.getCell(0).toString()).find());
					log.info("---row.getCell(1).toString()---{}", row.getCell(0).toString());
					log.info("---row.getCell(1).toString()---{}", row.getCell(1).toString());
					log.info("indexof---", row.getCell(1).getCellStyle());
					log.info("---newD---{}", row.getCell(1).toString());
					log.info("---newD---{}", row.getCell(2).toString());
					List<TbSysHotarea> list = hotareaDao.findByBranchCode(row.getCell(2).toString());
					if (!"0000".equals(row.getCell(2).toString())) {
						if (CollectionUtils.isEmpty(list)) {
							log.info("第" + (r + 1) + "行数据有问题，请仔细检查！");
						}
					}
					if (!Pattern.compile(reg).matcher(row.getCell(1).toString()).find()
							|| !Pattern.compile(reg).matcher(row.getCell(2).toString()).find()
							|| row.getCell(1).getCellStyle().getDataFormatString().indexOf("%") != -1) {
						log.info("第" + (r + 1) + "行数据有问题，请仔细检查！");
						sr.setFail();
						sr.setResult("第" + (r + 1) + "行数据有问题，请仔细检查！");
						return sr;
					}
				}
			}
		}
		// 新增发放
		TbSpScoreManual manual = new TbSpScoreManual();
		manual.setApplyTime(new Date());
		manual.setApplyer(userId);
		manual.setRemark(remark);
		// manual.setUrl(path);
		manual.setUrl(path.substring(path.indexOf("/sticcxb/"), path.length()));
		manual.setStatus(Constants.APPROVE_ADD);
		TbSpScoreManual dbmanual = manualDao.save(manual);
		manualId = dbmanual.getId();
		int people = 0;
		log.info("-----------校验通过==manualId--------{}", manualId);
		for (int nowsheet = 0; nowsheet < sheetNumber; nowsheet++) {
			// Excel工作表
			sheet = workbook.getSheetAt(nowsheet);
			for (int r = 1; r < totalRows; r++) {
				row = sheet.getRow(r);
				if (null == row) {
					continue;
				}
				if (null != row.getCell(0) && null != row.getCell(1)
						&& row.getCell(0).getCellType() != Cell.CELL_TYPE_BLANK
						&& row.getCell(1).getCellType() != Cell.CELL_TYPE_BLANK) {
					ulist = userDao.findByMobile(String.valueOf(row.getCell(0)));
					TbSpManualDetail tsmd = new TbSpManualDetail();
					log.info("电话：{}", row.getCell(0));
					log.info("积分：{}", row.getCell(1));
					log.info("电话：{}", String.valueOf(row.getCell(0)));
					log.info("积分：{}", row.getCell(1).toString());
					tsmd.setPhoneNo(String.valueOf(row.getCell(0)));
					// totalScore += row.getCell(1).getNumericCellValue();
					// tsmd.setScore(row.getCell(1).getNumericCellValue());
					BigDecimal total = new BigDecimal(totalScore);
					BigDecimal score = new BigDecimal(Double.parseDouble(row.getCell(1).toString()));
					totalScore = total.add(score).doubleValue();
					tsmd.setScore(score.doubleValue());
					String branchCode = String.valueOf(row.getCell(2));
					log.info(branchCode);
					// tsmd.setBranchCode(branchCode.substring(0, branchCode.indexOf(".")));
					tsmd.setBranchCode(branchCode);
					tsmd.setRemark(String.valueOf(row.getCell(3)) != null ? String.valueOf(row.getCell(3)) : "");
					tsmd.setTaskId(manualId);
					tsmd.setUserCode(ulist.get(0).getUserCode());
					manualDetailDao.save(tsmd);
					people++;
				}
			}
		}
		// 创建审批记录
		TbSpApprove tsa = new TbSpApprove();
		tsa.setStatus(Constants.FALSE);
		tsa.setApproveId(dbmanual.getId().toString());
		// tsa.setContent(jsonstring);
		// tsa.setOriginalStatus(status);
		tsa.setApplyTime(new Date());
		tsa.setApplyUser(userId);
		tsa.setFlowNo(flow.getFlowNo());
		tsa.setFlowType(Constants.FLOW_MANUAL_SCORE);
		tsa.setFlowNode(flow.getLastFlowNode());
		tsa.setType(Constants.MANUAL_APPROVE);
		approveDao.save(tsa);
		log.info("==========总分：{}", totalScore);
		dbmanual.setTotalScore(totalScore);
		dbmanual.setPeople(people);
		sr.setResult(manualDao.save(dbmanual));
		return sr;
	}

	@Override
	public ServiceResult beforeApprove(Integer id) {
		ServiceResult sr = new ServiceResult();

		List<TbSpManualDetail> dbDetail = manualDetailDao.findByTaskId(id);
		if (null == dbDetail || dbDetail.size() == 0) {
			sr.setFail();
			sr.setResult("无更多记录！");
			return sr;
		}
		List<String> str = Lists.newArrayList();
		for (TbSpManualDetail dt : dbDetail) {
			if (dt.getScore() < 0) {
				TbSpScore spScore = null;
				List<TbSpScore> dbscoreBu = scoreDao.findByUserCode(dt.getUserCode());
				if (null != dbscoreBu && dbscoreBu.size() != 0) {
					spScore = dbscoreBu.get(0);
					// if ((spScore.getEffctiveScore() + dt.getScore()) < 0) {
					BigDecimal s1 = new BigDecimal(spScore.getEffctiveScore());
					BigDecimal s2 = new BigDecimal(dt.getScore());
					// BigDecimal s3 = new BigDecimal(spScore.getNoeffctiveScore());
					if ((s1.add(s2).doubleValue()) < 0) {
						// if ((s1.add(s3).add(s2).doubleValue()) < 0) {
						str.add("电话为" + dt.getPhoneNo() + ",编码为" + dt.getUserCode() + "的用户有效积分不足扣减！");
					}
				} else {
					str.add("电话为" + dt.getPhoneNo() + ",编码为" + dt.getUserCode() + "的用户有效积分不足扣减！");
				}
			}
		}
		sr.setResult(str);
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult approve(String approveType, String id, String type, String remark) {
		ServiceResult sr = new ServiceResult();
		String userId = Current.userInfo.get().getUserId();
		SysOperationLog operLog = new SysOperationLog();
		operLog.setIP(Current.IP.get());
		operLog.setLevel("1");
		operLog.setOperationTime(new Date());
		operLog.setUserId(userId);
		// 审批信息
		List<TbSpApprove> dbtsalist = approveDao.findConfigByTypeAndApproveId(approveType, id.toString(),
				Constants.APPROVE_WAIT);
		TbSpApprove dbtsa = null;
		if (CollectionUtils.isEmpty(dbtsalist)) {
			sr.setFail();
			sr.setResult("未找到要审批的记录！");
			return sr;
		}
		dbtsa = dbtsalist.get(0);
		dbtsa.setUserId(userId);
		dbtsa.setApproveTime(new Date());
		dbtsa.setRemark(remark);
		if ("yes".equals(type)) {
			dbtsa.setStatus(Constants.APPROVE_YES);
			if (Constants.ACTIVITY_APPROVE.equals(approveType)) {// 审批活动添加
				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(),
						thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					JSONObject json = JSONObject.parseObject(dbtsa.getContent());
					TbSpActivity tsp = JSONObject.toJavaObject(json, TbSpActivity.class);
					SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
					String thisday = df.format(new Date());
					Date today;
					try {
						today = df.parse(thisday);
						if (tsp.getPlanStartTime().getTime() > today.getTime()) {// 如果计划开始时间大于审批时间，则实际开始时间等于计划时间
							tsp.setActualStartTime(tsp.getPlanStartTime());
						} else {
							tsp.setActualStartTime(new Date());
						}
						tsp.setApprover(userId);
						tsp.setApproveTime(new Date());
						activityDao.save(tsp);
						operLog.setContent(userId + "审批ID为" + id + "的添加--通过");
						operLog.setModule("活动管理");
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			} else if (Constants.BUDGET_APPROVE.equals(approveType)) {// 审批追加预算
				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(),
						thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					JSONObject json = JSONObject.parseObject(dbtsa.getContent());
					DrawReq drawReq = JSONObject.toJavaObject(json, DrawReq.class);
					TbSpActivity ac = activityDao.findById(drawReq.getId()).get();
					if (Constants.LUCK_DRAW_ACTIVITY.equals(ac.getActivityType())) {
						activityDao.updateBudgetAndTimes(Integer.parseInt(id), drawReq.getBudget(),
								drawReq.getAddDrawTimes(),
								drawReq.getAddSpecialTimes() != null ? drawReq.getAddSpecialTimes() : 0,
								dbtsa.getOriginalStatus());
					} else {
						activityDao.addBudget(Integer.parseInt(id), drawReq.getBudget(), dbtsa.getOriginalStatus());
					}
				}
				// 状态回写
				operLog.setContent(userId + "审批ID为" + id + "的追加预算--通过");
				operLog.setModule("活动管理");
			} else if (Constants.COMMISSION_APPROVE.equals(approveType)) {// 佣金配置审批
				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(),
						thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					List<TbSpStoreConfig> configList = JSON.parseArray(dbtsa.getContent(), TbSpStoreConfig.class);
					for (TbSpStoreConfig configs : configList) {
						List<TbSpStoreConfig> dblist = storeConfigDao.findByUserCodeAndProductId(configs.getUserCode(),
								configs.getProductId());
						if (CollectionUtils.isEmpty(dblist)) {
							TbSpStoreConfig config = new TbSpStoreConfig();
							config.setProductId(configs.getProductId());
							config.setRate(configs.getRate());
							config.setUserCode(configs.getUserCode());
							config.setProductName(configs.getProductName());
							storeConfigDao.save(config);
						} else {
							dblist.get(0).setRate(configs.getRate());
							storeConfigDao.save(dblist.get(0));
						}
					}
					userDao.updateConfigSerialNo(configList.get(0).getUserCode(), 0);
				}
				operLog.setContent(userId + "审批userCode为" + id + "的佣金配置--通过");
				operLog.setModule("佣金配置");
			} else if (Constants.AGREEMENT_COMMISSION_APPROVE.equals(approveType)) {// 业务关系代码佣金配置审批

				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(),
						thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					List<TbSpAgreementNoConfig> configList = JSON.parseArray(dbtsa.getContent(),
							TbSpAgreementNoConfig.class);
					for (TbSpAgreementNoConfig configs : configList) {
						List<TbSpAgreementNoConfig> dblist = agreementNoConfigDao
								.findByAgreementNoAndProductId(configs.getAgreementNo(), configs.getProductId());
						if (CollectionUtils.isEmpty(dblist)) {
							TbSpAgreementNoConfig config = new TbSpAgreementNoConfig();
							config.setProductId(configs.getProductId());
							config.setRate(configs.getRate());
							config.setAgreementNo(configs.getAgreementNo());
							config.setProductName(configs.getProductName());
							agreementNoConfigDao.save(config);
						} else {
							dblist.get(0).setRate(configs.getRate());
							agreementNoConfigDao.save(dblist.get(0));
						}
					}
				}
				operLog.setContent(userId + "审批业务关系代码为" + id + "的佣金配置--通过");
				operLog.setModule("佣金配置");
			} else if (Constants.ACTIVITY_STOP_APPROVE.equals(approveType)) {
				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(),
						thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					TbSpActivity dbac = activityDao.findById(Integer.parseInt(id)).get();
					dbac.setStatus(Constants.FALSE);
					dbac.setStopApprover(userId);
					dbac.setStopApproveTime(new Date());
					dbac.setActualEndTime(new Date());
					activityDao.save(dbac);
					operLog.setContent(userId + "审批ID为" + id + "的停止活动--通过");
					operLog.setModule("活动管理");
				}
			} else if (Constants.MANUAL_APPROVE.equals(approveType)) {

				TbSpFlowDetail thisDetail = flowDetailDao.findByNoAndNode(dbtsa.getFlowNo(), dbtsa.getFlowNode());
				TbSpFlowDetail upDetail = flowDetailDao.findByNoAndNode(thisDetail.getFlowNo(),
						thisDetail.getParentNode());
				if (!"firstNode".equals(upDetail.getParentNode())) {// 不是初始节点
					TbSpApprove newtsa = new TbSpApprove();
					newtsa.setApproveId(dbtsa.getApproveId());
					newtsa.setContent(dbtsa.getContent());
					newtsa.setFlowNo(dbtsa.getFlowNo());
					newtsa.setFlowType(dbtsa.getFlowType());
					newtsa.setFlowNode(upDetail.getFlowNode());
					newtsa.setStatus(Constants.APPROVE_WAIT);
					newtsa.setApplyTime(dbtsa.getApplyTime());
					newtsa.setApplyUser(dbtsa.getApplyUser());
					newtsa.setOriginalStatus(dbtsa.getOriginalStatus());
					newtsa.setType(dbtsa.getType());
					approveDao.save(newtsa);
				} else {
					Integer scoreDate = scoreConfigDao.findAllConfig().get(0).getPeriod();
					manualDao.updateStatus(Constants.TRUE, Integer.parseInt(id));// 手工发放
					TbSpScoreManual dnmanual = manualDao.findById(Integer.parseInt(id)).get();
					// 给客户分配/扣减积分
					List<TbSpManualDetail> detailList = manualDetailDao.findByTaskId(Integer.parseInt(id));
					for (TbSpManualDetail detail : detailList) {
						TbSpUser user = userDao.findByUserCode(detail.getUserCode());
						if (detail.getScore() > 0) {// 新增积分明细
							TbSpScoreLogIn in = new TbSpScoreLogIn();
							in.setReChangeScore(detail.getScore());// 应发不变，余额待确定
							in.setAcChangeScore(detail.getScore());// 实发不变，余额待确定
							in.setChangeType(Constants.CHANGE_TYYPE_HANDLE);
							in.setAccountType(Constants.FALSE);
							in.setGranter(userId);
							in.setReasonNo(detail.getTaskId().toString());
							in.setReason(detail.getRemark());
							in.setChangeTime(new Date());
							in.setBranchCode(detail.getBranchCode());
							in.setStatus(Constants.TRUE);
							in.setUserCode(detail.getUserCode());
							Date date = new Date();// 取时间
							in.setEffictiveDate(date);
							Calendar calendar = new GregorianCalendar();
							calendar.setTime(date);
							calendar.add(Calendar.YEAR, scoreDate);// 把日期往后增加n年.整数往后推,负数往前移动
							in.setInvalidDate(calendar.getTime());
							in.setTelephone(detail.getPhoneNo());
							in.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
							in.setRemark(detail.getRemark());
							// 客户积分总表
							// 查询有无记录
							TbSpScore newscore = null;
							List<TbSpScore> dbscore = scoreDao.findByUserCode(detail.getUserCode());
							if (null != dbscore && dbscore.size() != 0) {
								newscore = dbscore.get(0);
								BigDecimal s1 = new BigDecimal(newscore.getEffctiveScore());
								BigDecimal s2 = new BigDecimal(detail.getScore());
								Double ac = Math.floor(s1.add(s2).doubleValue());// 实发
								// 判断原本积分是否欠额
								if (newscore.getEffctiveScore() < 0) {
									in.setBalance(ac > 0 ? ac : 0);
								} else {
									in.setBalance(detail.getScore());
								}
								newscore.setEffctiveScore(ac);
								newscore.setStatisticTime(date);
								BigDecimal s3 = new BigDecimal(newscore.getSumScore());
								newscore.setSumScore(Math.floor(s3.add(s2).doubleValue()));
							} else {
								in.setBalance(detail.getScore());
								newscore = new TbSpScore();
								newscore.setEffctiveScore(detail.getScore());
								newscore.setNoeffctiveScore(0.00);
								newscore.setStatisticTime(date);
								newscore.setSumScore(detail.getScore());
								newscore.setOpenid(
										StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
								newscore.setUserCode(detail.getUserCode());
								newscore.setPhoneNo(detail.getPhoneNo());
							}
							scoreLogInDao.save(in);
							scoreDao.save(newscore);
						} else {// 扣减积分明细
							Date date = new Date();// 取时间
							// 客户积分总表
							// 查询有无记录
							TbSpScore newscore = null;
							List<TbSpScore> dbscore = scoreDao.findByUserCode(detail.getUserCode());
							if (null != dbscore && dbscore.size() != 0) {
								this.outScore(Constants.CHANGE_TYYPE_HANDLE, detail.getUserCode(),
										detail.getScore() * (-1), dnmanual.getRemark(), detail.getTaskId().toString());
							} else {
								TbSpScoreLogOut out = new TbSpScoreLogOut();
								out.setChangeType(Constants.CHANGE_TYYPE_HANDLE);
								out.setReChangeScore(detail.getScore());
								out.setAcChangeScore(detail.getScore());
								out.setGranter(userId);
								out.setReasonNo(detail.getTaskId().toString());
								out.setReason(detail.getRemark());
								out.setChangeTime(new Date());
								out.setEffictiveDate(date);
								out.setInvalidDate(date);
								out.setStatus(Constants.TRUE);
								out.setUserCode(detail.getUserCode());
								out.setTelephone(detail.getPhoneNo());
								out.setOpenId(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
								out.setRemark(detail.getRemark());
								scoreLogOutDao.save(out);
								// 总分表
								newscore = new TbSpScore();
								newscore.setEffctiveScore(detail.getScore());
								newscore.setNoeffctiveScore(0.00);
								newscore.setStatisticTime(date);
								newscore.setOpenid(
										StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
								newscore.setSumScore(0.00);
								newscore.setUserCode(detail.getUserCode());
								newscore.setPhoneNo(detail.getPhoneNo());
								scoreDao.save(newscore);
							}
						}
					}
					dnmanual.setApprover(userId);
					dnmanual.setApproveTime(new Date());
					manualDao.save(dnmanual);
					operLog.setContent(userId + "审批ID为" + id + "的手工发放--通过");
					operLog.setModule("手工发放管理");
				}
			}
		} else if ("no".equals(type)) {
			dbtsa.setStatus(Constants.APPROVE_NO);
			// 添加活动
			if (Constants.ACTIVITY_APPROVE.equals(approveType)) {
				TbSpActivity dbac = activityDao.findById(Integer.parseInt(id)).get();
				dbac.setStatus(Constants.APPROVE_FAIL);
				dbac.setApprover(userId);
				dbac.setApproveTime(new Date());
				activityDao.save(dbac);
				operLog.setContent(userId + "审批ID为" + id + "的活动的添加--拒绝");
				operLog.setModule("活动管理");
			}
			// 添加预算
			if (Constants.BUDGET_APPROVE.equals(approveType)) {
				activityDao.updateStatus(dbtsa.getOriginalStatus(), Integer.parseInt(id));// 状态回写
				operLog.setContent(userId + "审批ID为" + id + "的活动的添加预算--拒绝");
				operLog.setModule("活动管理");
			}
			if (Constants.COMMISSION_APPROVE.equals(approveType)) {
				operLog.setContent(userId + "审批用户编码为" + id + "的配置佣金比例--拒绝");
				operLog.setModule("配置用户佣金比例");
			}
			if (Constants.AGREEMENT_COMMISSION_APPROVE.equals(approveType)) {
				operLog.setContent(userId + "审批业务关系代码为" + id + "的配置佣金比例--拒绝");
				operLog.setModule("配置业务关系代码佣金比例");
			}
			// 停止活动
			if (Constants.ACTIVITY_STOP_APPROVE.equals(approveType)) {
				activityDao.updateStatus(dbtsa.getOriginalStatus(), Integer.parseInt(id));// 状态回写
				operLog.setContent(userId + "审批ID为" + id + "的活动的停止活动--拒绝");
				operLog.setModule("活动管理");
			}
			// 手工发放
			if (Constants.MANUAL_APPROVE.equals(approveType)) {
				TbSpScoreManual dnmanual = manualDao.findById(Integer.parseInt(id)).get();
				dnmanual.setApprover(userId);
				dnmanual.setApproveTime(new Date());
				dnmanual.setStatus(Constants.FALSE);
				manualDao.save(dnmanual);
				operLog.setContent(userId + "审批ID为" + id + "的活动的手工发放--拒绝");
				operLog.setModule("活动管理");
			}
		}
		operationLogDao.save(operLog);
		approveDao.save(dbtsa);
		sr.setSuccess();
		return sr;
	}

	// 手工发放查询
	@Override
	public ServiceResult listByhand(String startDate, String endDate, String status, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "status"));
		orders.add(new Order(Direction.DESC, "id"));
		Sort sort = new Sort(orders);
		String userId = Current.userId.get();
		Integer roleId = roleUserDao.findByUserid(userId).getRoleid();
		Page<TbSpScoreManual> page = manualDao.findAll(new Specification<TbSpScoreManual>() {
			public Predicate toPredicate(Root<TbSpScoreManual> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(startDate)) {
					log.info(startDate);
					predicate.add(cb.greaterThanOrEqualTo(root.get("applyTime").as(String.class), startDate));
				}
				if (StringUtils.isNotEmpty(endDate)) {
					log.info(endDate);
					predicate.add(cb.lessThanOrEqualTo(root.get("applyTime").as(String.class), endDate));
				}
				if (StringUtils.isNotEmpty(status) && !"-1".equals(status)) {
					log.info(status);
					predicate.add(cb.equal(root.get("status").as(String.class), status));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));

		List<TbSpScoreManual> list = page.getContent();
		if (null != page.getContent() && page.getContent().size() != 0) {
			TbSpApprove tsa = null;
			for (TbSpScoreManual manual : list) {
				tsa = approveDao.findByTypeAndApproveId(Constants.MANUAL_APPROVE, manual.getId().toString(),
						Constants.APPROVE_WAIT);
				tsa = approveDao.findApproveFlow(Constants.MANUAL_APPROVE, manual.getId().toString(),
						Constants.APPROVE_WAIT, Constants.FLOW_MANUAL_SCORE);

				if (null != tsa) {
					manual.setApprove(tsa);
					TbSpFlowDetail flowDetail = flowDetailDao.findByNoAndNode(tsa.getFlowNo(), tsa.getFlowNode());
					if (null != flowDetail && StringUtils.isNotBlank(flowDetail.getUserCode())) {// 用户审批
						String[] users = flowDetail.getUserCode().split("&");
						boolean b = Arrays.asList(users).contains(userId);
						if (b) {
							manual.setApproveAuth("true");
						} else {
							manual.setApproveAuth("false");
						}
					}
					if (null != flowDetail && StringUtils.isNotBlank(flowDetail.getRoleCode())) {// 角色审批
						String[] roles = flowDetail.getRoleCode().split("&");
						boolean b = Arrays.asList(roles).contains(roleId.toString());
						if (b) {
							manual.setApproveAuth("true");
						} else {
							manual.setApproveAuth("false");
						}
					}
				}
			}
		}
		sr.setResult(page);
		return sr;
	}

	// 发放明细查询
	@Override
	public ServiceResult inStorageDetail(String comCode, String startDate, String endDate, String changeType,
			String userCode, String branchCode, String policyNo, String telephone, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");
		Page<TbSpScoreLogIn> page = scoreLogInDao.findAll(new Specification<TbSpScoreLogIn>() {
			public Predicate toPredicate(Root<TbSpScoreLogIn> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(comCode)) {
					log.info(comCode);
					if (!"00000000".equals(comCode)) {
						if (!comCode.startsWith("WX") && !comCode.startsWith("BS")) {
							log.info(comCode.substring(0, 4));
							predicate.add(cb.equal(root.get("branchCode").as(String.class), comCode.substring(0, 4)));
						} else {
							Set<String> newList = new HashSet();
							List<TbSpUser> users = userDao.findByComCode(comCode);
							if (CollectionUtils.isNotEmpty(users)) {
								for (TbSpUser u : users) {
									newList.add(u.getUserCode());
								}
							}
							log.info("----newList----{}", newList.toString());
							Set<String> allcom = new HashSet();
							allcom = levelService.findAllNextBranchNo(newList, allcom);
							log.info("----allcom----{}", allcom.toString());
							allcom.add(comCode);
							allcom.addAll(newList);
							log.info("----allcom----{}", allcom.toString());
							if (CollectionUtils.isNotEmpty(allcom)) {
								In<String> in = cb.in(root.get("userCode").as(String.class));
								for (String ts : allcom) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(ts);
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
										in.value(userCodeBs);
									}
									in.value(ts);
								}
								predicate.add(in);
							} else {
								predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
							}
						}
					}
				} else {
					predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
				}

				if (StringUtils.isNotEmpty(changeType) && !"-1".equals(changeType)) {
					log.info(changeType);
					predicate.add(cb.equal(root.get("changeType").as(String.class), changeType));
				}
				if (StringUtils.isNotEmpty(branchCode)) {
					log.info(branchCode);
					predicate.add(cb.equal(root.get("branchCode").as(String.class), branchCode));
				}
				if (StringUtils.isNotEmpty(policyNo)) {
					log.info(policyNo);
					predicate.add(cb.equal(root.get("policyNo").as(String.class), policyNo));
				}
				if (StringUtils.isNotEmpty(userCode)) {
					log.info(userCode);
					String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
					TbSpUser user = userDao.findByUserCode(userCode);
					if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
						userCodeBs = user.getUserCodeBs();
						log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
								user.getUserCodeBs());
					}
					predicate.add(cb.or(cb.like(root.get("userCode").as(String.class), "%" + userCode + "%"),
							cb.like(root.get("userCode").as(String.class), "%" + userCodeBs + "%")));
				}
				if (StringUtils.isNotEmpty(telephone)) {
					log.info(telephone);
					predicate.add(cb.like(root.get("telephone").as(String.class), "%" + telephone + "%"));
				}
				if (StringUtils.isNotEmpty(startDate)) {
					log.info(startDate);
					predicate.add(cb.greaterThanOrEqualTo(root.get("changeTime").as(String.class), startDate));
				}
				if (StringUtils.isNotEmpty(endDate)) {
					log.info(endDate);
					predicate.add(cb.lessThanOrEqualTo(root.get("changeTime").as(String.class), endDate));
				}
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));
		sr.setResult(page);
		return sr;
	}

	// 客户积分扣减明细查询
	@Override
	public ServiceResult outStorageDetail(String comCode, String startDate, String endDate, String policyNo,
			String changeType, String userCode, String telephone, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");
		Page<TbSpScoreLogOut> page = scoreLogOutDao.findAll(new Specification<TbSpScoreLogOut>() {
			public Predicate toPredicate(Root<TbSpScoreLogOut> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();

				if (StringUtils.isNotEmpty(comCode)) {
					log.info(comCode);
					if (!"00000000".equals(comCode)) {
						if (!comCode.startsWith("WX") && !comCode.startsWith("BS")) {
							log.info(comCode.substring(0, 4));
							List<TbSpUser> users = userDao.findByBranchCode(comCode.substring(0, 4));
							if (CollectionUtils.isNotEmpty(users)) {
								In<String> in = cb.in(root.get("userCode").as(String.class));
								for (TbSpUser u : users) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(u.getUserCode());
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
										in.value(userCodeBs);
									}
									in.value(u.getUserCode());
								}
								predicate.add(in);
							} else {
								predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
							}
						} else {
							Set<String> newList = new HashSet();
							List<TbSpUser> users = userDao.findByComCode(comCode);
							if (CollectionUtils.isNotEmpty(users)) {
								for (TbSpUser u : users) {
									newList.add(u.getUserCode());
								}
							}
							log.info("----newList----{}", newList.toString());
							Set<String> allcom = new HashSet();
							allcom = levelService.findAllNextBranchNo(newList, allcom);
							log.info("----allcom----{}", allcom.toString());
							allcom.add(comCode);
							allcom.addAll(newList);
							log.info("----allcom----{}", allcom.toString());
							if (CollectionUtils.isNotEmpty(allcom)) {
								In<String> in = cb.in(root.get("userCode").as(String.class));
								for (String ts : allcom) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(ts);
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
										in.value(userCodeBs);
									}
									in.value(ts);
								}
								predicate.add(in);
							} else {
								predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
							}
						}
					}
				}

				if (StringUtils.isNotEmpty(changeType) && !"-1".equals(changeType)) {
					log.info(changeType);
					predicate.add(cb.equal(root.get("changeType").as(String.class), changeType));
				}
				if (StringUtils.isNotEmpty(policyNo)) {
					log.info(policyNo);
					predicate.add(cb.equal(root.get("policyNo").as(String.class), policyNo));
				}
				if (StringUtils.isNotEmpty(telephone)) {
					log.info(telephone);
					predicate.add(cb.like(root.get("telephone").as(String.class), "%" + telephone + "%"));
				}
				if (StringUtils.isNotEmpty(userCode)) {
					log.info(userCode);
					String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
					TbSpUser user = userDao.findByUserCode(userCode);
					if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
						userCodeBs = user.getUserCodeBs();
						log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
								user.getUserCodeBs());
					}
					predicate.add(cb.or(cb.like(root.get("userCode").as(String.class), "%" + userCode + "%"),
							cb.like(root.get("userCode").as(String.class), "%" + userCodeBs + "%")));
				}
				if (StringUtils.isNotEmpty(startDate)) {
					log.info(startDate);
					predicate.add(cb.greaterThanOrEqualTo(root.get("changeTime").as(String.class), startDate));
				}
				if (StringUtils.isNotEmpty(endDate)) {
					log.info(endDate);
					predicate.add(cb.lessThanOrEqualTo(root.get("changeTime").as(String.class), endDate));
				}
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));
		sr.setResult(page);
		return sr;
	}

	// // 积分用户规则发放
	// @Transactional(propagation = Propagation.REQUIRED) // 事务
	// @Override
	// public TbSpScoreLogIn ruleInScore(Integer productId, String policyNo, Double
	// amount, Date startDate) {
	// TbSpScoreLogIn ruleinscore = null;// 宝豆量
	// log.info("-----productId------{}", productId);
	// log.info("-----policyNo------{}", policyNo);
	// log.info("-----amount------{}", amount);
	// List<TbSpOrder> order = orderDao.findByPolicyNo(policyNo);
	// TbSpSaleLog saleLog = new TbSpSaleLog();
	// log.info("-----order size------{}", order.size());
	// String refereeUserCode = "";
	// if (CollectionUtils.isEmpty(order)) {
	// log.info("-----订单为空，返回---");
	// return ruleinscore;
	// }
	// if (StringUtils.isBlank(order.get(0).getRefereeId())) {// 是否有推荐人
	// log.info("-----规则发放没有推荐人---取当前用户---");
	// if (StringUtils.isNotBlank(order.get(0).getUserId())) {
	// refereeUserCode = order.get(0).getUserId();
	// } else {
	// log.info("-----规则发放没有推荐人、用户---");
	// return ruleinscore;
	// }
	// } else {
	// refereeUserCode = order.get(0).getRefereeId();
	// }
	// TbSpUser user = userDao.findByUserCode(refereeUserCode);
	// if (null == user) {
	// log.info("-----找不到用户{}-不获得积分-----", refereeUserCode);
	// return ruleinscore;
	// }
	// if ("1".equals(user.getUserType()) || "2".equals(user.getUserType()) ||
	// "5".equals(user.getUserType())) {
	//
	// if (StringUtils.isBlank(user.getIdNumber())) {
	// log.info("-----未实名-不获得积分-----");
	// return ruleinscore;
	// }
	// if (Constants.FALSE.equals(user.getStoreFlag())) {
	// log.info("-----未开店-不获得积分-----");
	// return ruleinscore;
	// }
	// List<TbSpApplicant> applicant =
	// applicantDao.findByOrderNo(order.get(0).getOrderNo());
	// if (CollectionUtils.isNotEmpty(applicant)) {
	// for (TbSpApplicant at : applicant) {
	// log.info("at.getCarId():{}", at.getCarId());
	// if (at.getCarId().equals(user.getIdNumber())) {
	// log.info("-----积分用户投保人、被保人是本人不获得积分------{}");
	// return ruleinscore;
	// }
	// }
	// }
	// List<TbSpScoreLogIn> dbin =
	// scoreLogInDao.findByPolicyNo(Constants.CHANGE_TYYPE_RULE, policyNo);
	// if (CollectionUtils.isNotEmpty(dbin)) {
	// log.info("-----该保单号赠送过积分，不再赠送------{}");
	// return ruleinscore;
	// }
	// log.info("-----no cuo 1------{}");
	// TbSpScoreConfig scoreConfig = scoreConfigDao.findAllConfig().get(0);
	// Double feeRate = scoreConfig.getFeeRate();
	// log.info("-----no cuo 2------{}");
	// String productName = null;
	// TbSpProduct product = productDao.findById(productId).get();
	// if (null != product) {
	// productName = product.getProductCname();
	// log.info("-----productName------{}", productName);
	// } else {
	// return ruleinscore;
	// }
	// log.info("-----no cuo 3--userCode--获得积分--{}", refereeUserCode);
	// Double rate = 0.00;
	// Double configRate = null;// 配置的佣金比例
	// // 查看店铺佣金比例
	// String branchCode = "";
	// List<TbSpStoreConfig> dblist =
	// storeConfigDao.findByUserCodeAndProductId(refereeUserCode, productId);
	// if (CollectionUtils.isNotEmpty(dblist)) {
	// log.info("-----店铺佣金---");
	// configRate = dblist.get(0).getRate();
	// } else {
	// log.info("-----非店铺佣金---");
	// // 店铺为空查询业务关系代码的佣金配置
	// if (StringUtils.isNotBlank(user.getAgrementNo())) {
	// List<TbSpAgreementNoConfig> dbagreelist =
	// agreementNoConfigDao.findByAgreementNoAndProductId(user.getAgrementNo(),
	// productId);
	// if (CollectionUtils.isNotEmpty(dbagreelist)) {
	// log.info("-----业务关系代码佣金---");
	// configRate = dbagreelist.get(0).getRate();
	// }
	// }
	// }
	// log.info("-----configRate configRate configRate------{}", configRate);
	// if (null == configRate) {
	// if (StringUtils.isNotBlank(user.getBranchCode())) {
	// branchCode = user.getBranchCode();
	// } else {
	// String areaCode = "";
	// if (StringUtils.isNotBlank(user.getAreaCode())) {
	// areaCode = user.getAreaCode();
	// } else {
	// areaCode = order.get(0).getBranchCode();
	// }
	// branchCode = tbSysHotareaDao.findByAreaCode(areaCode).getBranchCode();
	// }
	// if (StringUtils.isNotBlank(branchCode)) {
	// // List<TbSysHotarea> dbbranch =
	// tbSysHotareaDao.findByBranchCode(branchCode);
	// // if (CollectionUtils.isNotEmpty(dbbranch)) {
	// // List<TbSpAgreementNoConfig> dbCommonAgreelist =
	// //
	// agreementNoConfigDao.findByAgreementNoAndProductId(dbbranch.get(0).getAgreementNo(),
	// // productId);
	// // if (CollectionUtils.isNotEmpty(dbCommonAgreelist)) {
	// // log.info("-----通用业务关系代码佣金---");
	// // rate = dbCommonAgreelist.get(0).getRate();
	// // }else {
	// // log.info("-----no cuo dbbranch---rate---{}", branchCode);
	// // branchCode = branchSetService.cutBranchCode(branchCode);
	// // rate = productConfigDao.findByProAndBranchCode(productId,
	// // branchCode).getRate();
	// // }
	// // }else {
	// log.info("-----no cuo branchCode---rate---{}", branchCode);
	// branchCode = branchSetService.cutBranchCode(branchCode);
	// rate = productConfigDao.findByProAndBranchCode(productId,
	// branchCode).getRate();
	// // }
	// }
	// } else {
	// rate = configRate;
	// }
	//
	// log.info("-----no cuo 4------");
	// log.info("-----rate rate rate------{}", rate);
	//
	// BigDecimal b1 = new BigDecimal(1);
	// BigDecimal b11 = new BigDecimal(feeRate);
	// BigDecimal b2 = new BigDecimal(rate);
	// BigDecimal b3 = new BigDecimal(amount);
	// BigDecimal b4 = new BigDecimal(scoreConfig.getRate());
	// // Double inScore = b3.multiply(b2).multiply(b1).multiply(b4).setScale(0,
	// // BigDecimal.ROUND_HALF_UP).doubleValue();
	// Double inScore = b3.multiply(b4).multiply(b2).divide(b1.add(b11), 4,
	// BigDecimal.ROUND_HALF_UP).setScale(0, BigDecimal.ROUND_HALF_UP)
	// .doubleValue();
	// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
	// String thisday = df.format(new Date());
	// try {
	// saleLog.setOperation("签单积分");
	// saleLog.setRequestData(refereeUserCode);
	// saleLog.setUserCode(refereeUserCode);
	// saleLog.setRequestTime(new Date());
	// saleLog.setMark("签单积分");
	// Date today = df.parse(thisday);
	// TbSpScoreLogIn in = new TbSpScoreLogIn();
	// log.info("-----no cuo 5------{}", inScore);
	// in.setChangeType(Constants.CHANGE_TYYPE_RULE);
	// in.setReason(productName);
	// in.setChangeTime(new Date());
	// in.setStatus(Constants.TRUE);
	// in.setUserCode(refereeUserCode);
	// in.setPolicyNo(policyNo);
	// in.setReasonNo(policyNo);
	// in.setGranter("system");
	// String areaCode = policyNo.substring(6, 10);
	// List<TbSysHotarea> area = tbSysHotareaDao.findLikeBranchCodeLike(areaCode);
	// if (CollectionUtils.isNotEmpty(area)) {
	// in.setBranchCode(area.get(0).getBranchCode());
	// }
	// log.info("-----no cuo 7------");
	// in.setEffictiveDate(startDate);
	// Calendar calendar = new GregorianCalendar();
	// calendar.setTime(startDate);
	// calendar.add(Calendar.YEAR, scoreConfig.getPeriod());//
	// 把日期往后增加n年.整数往后推,负数往前移动
	// in.setInvalidDate(calendar.getTime());
	// in.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() :
	// null);
	// in.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId()
	// : null);
	// in.setRemark("签单积分");
	// in.setReChangeScore(inScore);// 应发
	// // 客户积分总表
	// // 查询有无记录
	// TbSpScore newscore = null;
	// List<TbSpScore> dbscore = scoreDao.findByUserCode(refereeUserCode);
	// log.info("-----no cuo 8------");
	// if (CollectionUtils.isNotEmpty(dbscore)) {
	// log.info("-----no cuo 9------");
	// newscore = dbscore.get(0);
	// BigDecimal s1 = new BigDecimal(newscore.getNoeffctiveScore());
	// BigDecimal s2 = new BigDecimal(inScore);
	// BigDecimal s3 = new BigDecimal(newscore.getEffctiveScore());
	// Double re = Math.floor(s1.add(s2).doubleValue());// 应发
	// Double ac = Math.floor(s3.add(s2).doubleValue());// 实发
	// if (startDate.getTime() > today.getTime()) {
	// // 定时任务时确定实发
	// log.info("原待生效：" + s1.doubleValue() + ",获得待生效:" + inScore + "后待生效变为" +
	// re.doubleValue());
	// saleLog.setResponseData("原待生效：" + s1.doubleValue() + ",获得待生效:" + inScore +
	// "后待生效变为" + re.doubleValue());
	// in.setAcChangeScore(0.00);
	// in.setBalance(0.00);
	// newscore.setNoeffctiveScore(re);
	// } else {
	// log.info("原生效：" + s3.doubleValue() + ",获得生效:" + inScore + "后生效变为" +
	// ac.doubleValue());
	// saleLog.setResponseData("原生效：" + s3.doubleValue() + ",获得生效:" + inScore +
	// "后生效变为" + ac.doubleValue());
	// in.setAcChangeScore(inScore);
	// log.info("-----签单积分立即生效-----");
	// if (newscore.getEffctiveScore() < 0) {// 原本积分欠额
	// in.setBalance(ac > 0 ? ac : 0);
	// } else {
	// in.setBalance(inScore);
	// }
	// newscore.setEffctiveScore(ac);
	// }
	// newscore.setStatisticTime(new Date());
	// newscore.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ?
	// user.getWxOpenId() : null);
	// newscore.setSumScore(Math.floor(new
	// BigDecimal(newscore.getSumScore()).add(s2).doubleValue()));
	// } else {// 新建记录
	// log.info("-----no cuo 10-----}");
	// newscore = new TbSpScore();
	// newscore.setOpenid(StringUtils.isNotBlank(user.getWxOpenId()) ?
	// user.getWxOpenId() : null);
	// if (startDate.getTime() > today.getTime()) {
	// log.info("无原待生效，加上新待生效变为：" + inScore);
	// saleLog.setResponseData("无原待生效，加上新待生效变为：" + inScore);
	// in.setAcChangeScore(0.00);
	// in.setBalance(0.00);
	// newscore.setNoeffctiveScore(inScore);
	// newscore.setEffctiveScore(0.00);
	// } else {
	// log.info("无原生效，加上新生效变为：" + inScore);
	// saleLog.setResponseData("无原生效，加上新生效变为：" + inScore);
	// in.setAcChangeScore(inScore);
	// in.setBalance(inScore);
	// newscore.setEffctiveScore(inScore);
	// newscore.setNoeffctiveScore(0.00);
	// }
	// newscore.setStatisticTime(new Date());
	// newscore.setSumScore(inScore);
	// newscore.setUserCode(refereeUserCode);
	// newscore.setPhoneNo(StringUtils.isNotEmpty(user.getMobile()) ?
	// user.getMobile() : null);
	// }
	// scoreLogInDao.save(in);
	// ruleinscore = in;
	// scoreDao.save(newscore);
	// spSaleLogDao.save(saleLog);
	// } catch (ParseException e) {
	// e.printStackTrace();
	// }
	// } else {
	// // 3&4用户类型推送0积分
	// ruleinscore = new TbSpScoreLogIn();
	// ruleinscore.setReChangeScore(0.00);
	// }
	//
	// log.info("-----no cuo 11------");
	// return ruleinscore;
	// }

	// 积分用户规则发放
	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public TbSpScoreLogIn ruleInScore(TbSpOrder order, TbSpUser user) {
		TbSpScoreLogIn ruleinscore = new TbSpScoreLogIn();// 宝豆量
		TbSpSaleLog saleLog = new TbSpSaleLog();
		String refereeUserCode = user.getUserCode();
		Integer productId = Integer.parseInt(order.getProductId());
		String policyNo = order.getPolicyNo();
		Double amount = order.getAmount();
		Date startDate = order.getStartDate();
		saleLog.setOperation("签单积分");
		saleLog.setRequestData(refereeUserCode);
		saleLog.setUserCode(refereeUserCode);
		saleLog.setRequestTime(new Date());
		saleLog.setMark("签单积分");
		if ("1".equals(user.getUserType()) || "2".equals(user.getUserType()) || "5".equals(user.getUserType())) {
			if (StringUtils.isBlank(user.getIdNumber())) {
				log.info("-----未实名-不获得积分-----");
				saleLog.setResponseData("未实名-不获得积分");
				spSaleLogDao.save(saleLog);
				ruleinscore.setStatus(Constants.FALSE);
				return ruleinscore;
			}
			if (Constants.FALSE.equals(user.getStoreFlag())) {
				log.info("-----未开店-不获得积分-----");
				saleLog.setResponseData("未实名-不获得积分");
				spSaleLogDao.save(saleLog);
				ruleinscore.setStatus(Constants.FALSE);
				return ruleinscore;
			}
			List<TbSpApplicant> applicant = applicantDao.findByOrderNo(order.getOrderNo());
			if (CollectionUtils.isNotEmpty(applicant)) {
				for (TbSpApplicant at : applicant) {
					log.info("at.getCarId():{}", at.getCarId());
					if (at.getCarId().equals(user.getIdNumber())) {
						log.info("-----积分用户投保人、被保人是本人不获得积分------{}");
						saleLog.setResponseData("积分用户投保人、被保人是本人不获得积分");
						spSaleLogDao.save(saleLog);
						ruleinscore.setStatus(Constants.FALSE);
						return ruleinscore;
					}
				}
			}
			List<String> changeType = Lists.newArrayList();
			changeType.add(Constants.CHANGE_TYYPE_RULE);
			TbSpScoreLogIn dbin = scoreLogInDao.findByUCodeAndPolicyNoAndType(user.getUserCode(), policyNo, changeType);
			if (null != dbin) {
				log.info("-----该保单号赠送过积分，不再赠送------{}");
				saleLog.setResponseData("该保单号赠送过积分，不再赠送");
				spSaleLogDao.save(saleLog);
				ruleinscore.setStatus(Constants.FALSE);
				return ruleinscore;
			}
			log.info("-----no cuo  1------{}");
			TbSpScoreConfig scoreConfig = scoreConfigDao.findAllConfig().get(0);
			Double feeRate = scoreConfig.getFeeRate();
			log.info("-----no cuo  2------{}");
			String productName = null;
			TbSpProduct product = productDao.findById(productId).get();
			if (null != product) {
				productName = product.getProductCname();
				log.info("-----productName------{}", productName);
			} else {
				ruleinscore.setStatus(Constants.FALSE);
				saleLog.setResponseData("无产品信息");
				spSaleLogDao.save(saleLog);
				return ruleinscore;
			}
			log.info("-----no cuo  3--userCode--获得积分--{}", refereeUserCode);
			Double rate = findRate(order, user);

			// Double rate = 0.00;
			// Double configRate = null;// 配置的佣金比例
			// // 查看店铺佣金比例
			// String branchCode = "";
			// List<TbSpStoreConfig> dblist =
			// storeConfigDao.findByUserCodeAndProductId(refereeUserCode, productId);
			// if (CollectionUtils.isNotEmpty(dblist)) {
			// log.info("-----店铺佣金---");
			// configRate = dblist.get(0).getRate();
			// } else {
			// log.info("-----非店铺佣金---");
			// // 店铺为空查询业务关系代码的佣金配置
			// if (StringUtils.isNotBlank(user.getAgrementNo())) {
			// List<TbSpAgreementNoConfig> dbagreelist =
			// agreementNoConfigDao.findByAgreementNoAndProductId(user.getAgrementNo(),
			// productId);
			// if (CollectionUtils.isNotEmpty(dbagreelist)) {
			// log.info("-----业务关系代码佣金---");
			// configRate = dbagreelist.get(0).getRate();
			// }
			// }
			// }
			// log.info("-----configRate configRate configRate------{}", configRate);
			// if (null == configRate) {
			// if (StringUtils.isNotBlank(user.getBranchCode())) {
			// branchCode = user.getBranchCode();
			// } else {
			// String areaCode = "";
			// if (StringUtils.isNotBlank(user.getAreaCode())) {
			// areaCode = user.getAreaCode();
			// } else {
			// areaCode = order.getBranchCode();
			// }
			// branchCode = tbSysHotareaDao.findByAreaCode(areaCode).getBranchCode();
			// }
			// if (StringUtils.isNotBlank(branchCode)) {
			// log.info("-----no cuo branchCode---rate---{}", branchCode);
			// branchCode = branchSetService.cutBranchCode(branchCode);
			// rate = productConfigDao.findByProAndBranchCode(productId,
			// branchCode).getRate();
			// // }
			// }
			// } else {
			// rate = configRate;
			// }
			log.info("-----no cuo  4------");
			log.info("-----rate   rate    rate------{}", rate);
			BigDecimal b1 = new BigDecimal(1);
			BigDecimal b11 = new BigDecimal(feeRate);
			BigDecimal b2 = new BigDecimal(rate);
			BigDecimal b3 = new BigDecimal(amount);
			BigDecimal b4 = new BigDecimal(scoreConfig.getRate());
			Double inScore = b3.multiply(b4).multiply(b2).divide(b1.add(b11), 4, BigDecimal.ROUND_HALF_UP)
					.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
			String thisday = df.format(new Date());
			try {
				Date today = df.parse(thisday);
				TbSpScoreLogIn in = new TbSpScoreLogIn();
				log.info("-----no cuo  5------{}", inScore);
				in.setChangeType(Constants.CHANGE_TYYPE_RULE);
				in.setAccountType(Constants.FALSE);
				in.setReason(productName);
				in.setChangeTime(new Date());
				in.setStatus(Constants.TRUE);
				in.setUserCode(refereeUserCode);
				in.setPolicyNo(policyNo);
				in.setReasonNo(policyNo);
				in.setGranter("system");
				String areaCode = policyNo.substring(6, 10);
				List<TbSysHotarea> area = tbSysHotareaDao.findLikeBranchCodeLike(areaCode);
				if (CollectionUtils.isNotEmpty(area)) {
					in.setBranchCode(area.get(0).getBranchCode());
				}
				log.info("-----no cuo  7------");
				in.setEffictiveDate(startDate);
				Calendar calendar = new GregorianCalendar();
				calendar.setTime(startDate);
				calendar.add(Calendar.YEAR, scoreConfig.getPeriod());// 把日期往后增加n年.整数往后推,负数往前移动
				in.setInvalidDate(calendar.getTime());
				in.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
				in.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
				in.setRemark("签单积分");
				in.setReChangeScore(inScore);// 应发
				// 客户积分总表
				// 查询有无记录
				TbSpScore newscore = null;
				List<TbSpScore> dbscore = scoreDao.findByUserCode(refereeUserCode);
				log.info("-----no cuo  8------");
				if (CollectionUtils.isNotEmpty(dbscore)) {
					log.info("-----no cuo  9------");
					newscore = dbscore.get(0);
					BigDecimal s1 = new BigDecimal(newscore.getNoeffctiveScore());
					BigDecimal s2 = new BigDecimal(inScore);
					BigDecimal s3 = new BigDecimal(newscore.getEffctiveScore());
					Double re = Math.floor(s1.add(s2).doubleValue());// 应发
					Double ac = Math.floor(s3.add(s2).doubleValue());// 实发
					if (startDate.getTime() > today.getTime()) {
						// 定时任务时确定实发
						log.info("原待生效：" + s1.doubleValue() + ",获得待生效:" + inScore + "后待生效变为" + re.doubleValue());
						saleLog.setResponseData(
								"原待生效：" + s1.doubleValue() + ",获得待生效:" + inScore + "后待生效变为" + re.doubleValue());
						in.setAcChangeScore(0.00);
						in.setBalance(0.00);
						newscore.setNoeffctiveScore(re);
					} else {
						log.info("原生效：" + s3.doubleValue() + ",获得生效:" + inScore + "后生效变为" + ac.doubleValue());
						saleLog.setResponseData(
								"原生效：" + s3.doubleValue() + ",获得生效:" + inScore + "后生效变为" + ac.doubleValue());
						in.setAcChangeScore(inScore);
						log.info("-----签单积分立即生效-----");
						if (newscore.getEffctiveScore() < 0) {// 原本积分欠额
							in.setBalance(ac > 0 ? ac : 0);
						} else {
							in.setBalance(inScore);
						}
						newscore.setEffctiveScore(ac);
					}
					newscore.setStatisticTime(new Date());
					newscore.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
					newscore.setSumScore(Math.floor(new BigDecimal(newscore.getSumScore()).add(s2).doubleValue()));
				} else {// 新建记录
					log.info("-----no cuo  10-----}");
					newscore = new TbSpScore();
					newscore.setOpenid(StringUtils.isNotBlank(user.getWxOpenId()) ? user.getWxOpenId() : null);
					if (startDate.getTime() > today.getTime()) {
						log.info("无原待生效，加上新待生效变为：" + inScore);
						saleLog.setResponseData("无原待生效，加上新待生效变为：" + inScore);
						in.setAcChangeScore(0.00);
						in.setBalance(0.00);
						newscore.setNoeffctiveScore(inScore);
						newscore.setEffctiveScore(0.00);
					} else {
						log.info("无原生效，加上新生效变为：" + inScore);
						saleLog.setResponseData("无原生效，加上新生效变为：" + inScore);
						in.setAcChangeScore(inScore);
						in.setBalance(inScore);
						newscore.setEffctiveScore(inScore);
						newscore.setNoeffctiveScore(0.00);
					}
					newscore.setStatisticTime(new Date());
					newscore.setSumScore(inScore);
					newscore.setUserCode(refereeUserCode);
					newscore.setPhoneNo(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
				}
				scoreLogInDao.save(in);
				ruleinscore = in;
				scoreDao.save(newscore);
				spSaleLogDao.save(saleLog);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		} else {
			// 3&4用户类型推送0积分
			ruleinscore = new TbSpScoreLogIn();
			ruleinscore.setReChangeScore(0.00);
		}
		log.info("-----no cuo  11------");
		return ruleinscore;
	}

	// 寻找佣金比例
	public Double findRate(TbSpOrder order, TbSpUser user) {
		String refereeUserCode = user.getUserCode();
		Integer productId = Integer.parseInt(order.getProductId());
		log.info("----productId---{}", productId);
		Double rate = 0.00;
		Double configRate = null;// 配置的佣金比例
		// 查看店铺佣金比例
		String branchCode = "0000";
		List<TbSpStoreConfig> dblist = storeConfigDao.findByUserCodeAndProductId(refereeUserCode, productId);
		if (CollectionUtils.isNotEmpty(dblist)) {
			log.info("-----店铺佣金---");
			configRate = dblist.get(0).getRate();
		} else {
			log.info("-----非店铺佣金---");
			// 店铺为空查询业务关系代码的佣金配置
			if (StringUtils.isNotBlank(user.getAgrementNo())) {
				List<TbSpAgreementNoConfig> dbagreelist = agreementNoConfigDao
						.findByAgreementNoAndProductId(user.getAgrementNo(), productId);
				if (CollectionUtils.isNotEmpty(dbagreelist)) {
					log.info("-----业务关系代码佣金---");
					configRate = dbagreelist.get(0).getRate();
				}
			}
		}
		log.info("-----configRate------{}", configRate);
		if (null == configRate) {
			// if (StringUtils.isNotBlank(user.getBranchCode())) {
			// branchCode = user.getBranchCode();
			// } else {
			// String areaCode = "";
			// if (StringUtils.isNotBlank(user.getAreaCode())) {
			// areaCode = user.getAreaCode();
			// } else {
			// areaCode = order.getBranchCode();
			// }
			// branchCode = tbSysHotareaDao.findByAreaCode(areaCode).getBranchCode();
			// }
			// if (StringUtils.isNotBlank(branchCode)) {
			// log.info("-----no cuo branchCode---rate---{}", branchCode);
			// branchCode = branchSetService.cutBranchCode(branchCode);
			rate = productConfigDao.findByProAndBranchCode(productId, branchCode).getRate();
			// }
			// }
		} else {
			rate = configRate;
		}
		log.info("-----rate------{}", rate);
		return rate;
	}

	// 积分用户退保返还待生效积分
	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public int ruleOutScore(String policyNo, String userCode) {
		TbSpUser user = userDao.findByUserCode(userCode);

		List<TbSpOrder> order = orderDao.findByPolicyNo(policyNo);
		if (CollectionUtils.isEmpty(order)) {
			return 0;
		}
		if ("1".equals(user.getUserType()) || "2".equals(user.getUserType()) || "5".equals(user.getUserType())) {
			String productName = order.get(0).getProductName();
			List<TbSpScoreLogIn> dbin = scoreLogInDao.findInScoreHis(policyNo, userCode);
			if (CollectionUtils.isNotEmpty(dbin)) {
				Double acInScore = dbin.get(0).getReChangeScore();
				// 实收=应收
				dbin.get(0).setAcChangeScore(acInScore);
				scoreLogInDao.save(dbin.get(0));
				TbSpScoreLogOut out = new TbSpScoreLogOut();
				out.setChangeType(Constants.CHANGE_TYYPE_TB);
				out.setReChangeScore(acInScore);
				out.setAcChangeScore(acInScore);
				out.setReason(productName);
				Date date = new Date();// 取时间
				out.setChangeTime(date);
				out.setEffictiveDate(date);
				out.setInvalidDate(date);
				out.setStatus(Constants.TRUE);
				out.setReasonNo(policyNo);
				out.setUserCode(userCode);
				out.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
				out.setOpenId(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
				out.setRemark(productName);
				scoreLogOutDao.save(out);
				// 客户积分总表
				TbSpScore dbscore = scoreDao.findByUserCode(userCode).get(0);
				if (null != dbscore) {
					BigDecimal s1 = new BigDecimal(dbscore.getNoeffctiveScore());
					BigDecimal s2 = new BigDecimal(acInScore);
					dbscore.setNoeffctiveScore(Math.floor(s1.subtract(s2).doubleValue()));
					dbscore.setStatisticTime(date);
					scoreDao.save(dbscore);
					return 1;
				}
			}
		}
		return 0;
	}

	// // 公共扣减方法
	// @Transactional(propagation = Propagation.REQUIRED) // 事务
	// @Override
	// public List<TbSpScoreLogIn> outScore(String type, String userCode, Double
	// amount, String reason, String policyNo) {
	//
	// List<TbSpScoreLogIn> inToOutList = Lists.newArrayList();
	// TbSpUser user = userDao.findByUserCode(userCode);
	// // 积分总额-时间排序
	// List<TbSpScoreLogIn> allin = scoreLogInDao.findAllEffect(userCode);
	// Double score = 0.00;
	// for (TbSpScoreLogIn in : allin) {
	// // score += in.getBalance();
	// BigDecimal s1 = new BigDecimal(score);
	// BigDecimal s2 = new BigDecimal(in.getBalance());
	// score = Math.floor(s1.add(s2).doubleValue());
	// log.info("积分总额score{}", score.toString());
	// }
	// // if (score < amount) {
	// // return inToOutList;
	// // }
	//
	// Double acInScore = amount;
	// Double outScore = 0.00;
	// Date date = null;
	// for (int i = 0; i < allin.size(); i++) {
	// Double balance = allin.get(i).getBalance();
	// log.info(balance.toString());
	// log.info(acInScore.toString());
	// log.info(outScore.toString());
	// if (outScore >= amount) {
	// break;
	// }
	// TbSpScoreLogIn newin = new TbSpScoreLogIn();
	// try {
	// BeanUtilExt.copyProperties(newin, allin.get(i));
	// } catch (InvocationTargetException e) {
	// e.printStackTrace();
	// } catch (IllegalAccessException e) {
	// e.printStackTrace();
	// }
	// inToOutList.add(newin);
	// BigDecimal s1 = new BigDecimal(balance);
	// BigDecimal s2 = new BigDecimal(acInScore);
	// BigDecimal s3 = new BigDecimal(outScore);
	// if (balance >= acInScore) {// 足以扣减
	// allin.get(i).setBalance(Math.floor(s1.subtract(s2).doubleValue()));
	// scoreLogInDao.save(allin.get(i));
	// acInScore = 0.00;
	// outScore = amount;
	// break;
	// } else if (balance < acInScore) {// 不足以扣减
	// allin.get(i).setBalance(0.00);
	// scoreLogInDao.save(allin.get(i));
	// // 递减
	// acInScore = Math.floor(s2.subtract(s1).doubleValue());
	// outScore = Math.floor(s3.add(s1).doubleValue());
	// }
	// }
	// log.info("-----生效扣完之后还剩余{}没扣，--扣减待生效。", acInScore);
	// Double acWaitInScore = acInScore;
	// if (acWaitInScore > 0) {
	// // 积分待生效总额-时间排序
	// List<TbSpScoreLogIn> allwaitin = scoreLogInDao.findAllWaitEffect(userCode);
	// if (CollectionUtils.isNotEmpty(allwaitin)) {
	// log.info("----扣减待生效----");
	// for (TbSpScoreLogIn waitin : allwaitin) {
	// if (outScore >= amount) {
	// break;
	// }
	// // 将实发设值为应发
	// BigDecimal s1 = new BigDecimal(waitin.getReChangeScore());
	// BigDecimal s4 = new BigDecimal(waitin.getAcChangeScore());
	// BigDecimal s2 = new BigDecimal(acWaitInScore);
	// BigDecimal s3 = new BigDecimal(outScore);
	// // 待生效可用余额
	// Double reChangeScore = s1.subtract(s4).doubleValue();// 待生效可用余额
	// if (reChangeScore >= acWaitInScore) {// 足以扣减
	// // waitin.setAcChangeScore(reChangeScore);
	// waitin.setAcChangeScore(s4.add(s2).doubleValue());
	// scoreLogInDao.save(waitin);
	// acWaitInScore = 0.00;
	// outScore = amount;
	// break;
	// } else if (reChangeScore < acInScore) {// 不足以扣减
	// waitin.setAcChangeScore(reChangeScore);
	// scoreLogInDao.save(waitin);
	// acWaitInScore = Math.floor(s2.subtract(s1).doubleValue());
	// outScore = Math.floor(s3.add(s1).doubleValue());
	// }
	// inToOutList.add(waitin);
	// }
	// }
	// }
	// if (acWaitInScore > 0) {// 待生效扣完之后还是不足，则记录一条退保差额扣减
	// TbSpScoreLogOut out = new TbSpScoreLogOut();
	// out.setChangeType(Constants.CHANGE_TYYPE_TBBalance);
	// out.setReChangeScore(Math.floor(acWaitInScore * (-1)));
	// out.setAcChangeScore(Math.floor(acWaitInScore * (-1)));
	// out.setReason("差额");
	// date = new Date();// 取时间
	// out.setChangeTime(date);
	// out.setGranter("system");
	// out.setEffictiveDate(date);
	// out.setInvalidDate(date);
	// out.setStatus(Constants.TRUE);
	// out.setPolicyNo(policyNo);
	// out.setReasonNo(policyNo);
	// out.setUserCode(userCode);
	// out.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile()
	// : null);
	// out.setOpenId(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() :
	// null);
	// out.setRemark("差额");
	// scoreLogOutDao.save(out);
	//
	// }
	// // 记录扣减
	// TbSpScoreLogOut out = new TbSpScoreLogOut();
	// out.setChangeType(type);
	// out.setReChangeScore(Math.floor(amount * (-1)));
	// out.setAcChangeScore(Math.floor(amount * (-1)));
	// out.setReason(reason);
	// date = new Date();// 取时间
	// out.setChangeTime(date);
	// out.setGranter("system");
	// out.setEffictiveDate(date);
	// out.setInvalidDate(date);
	// out.setStatus(Constants.TRUE);
	// out.setReasonNo(policyNo);
	// out.setPolicyNo(policyNo);
	// out.setUserCode(userCode);
	// out.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile()
	// : null);
	// out.setOpenId(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() :
	// null);
	// out.setRemark(reason);
	// scoreLogOutDao.save(out);
	// // 客户积分总表
	// TbSpScore dbscore = scoreDao.findByUserCode(userCode).get(0);
	// if (null != dbscore) {
	// BigDecimal s1 = new BigDecimal(dbscore.getEffctiveScore());
	// BigDecimal s2 = new BigDecimal(amount);// 扣减已生效额度
	// BigDecimal s3 = new BigDecimal(acInScore);// 扣减待生效额度
	// BigDecimal s4 = new BigDecimal(dbscore.getNoeffctiveScore());
	// // dbscore.setEffctiveScore(dbscore.getEffctiveScore() - amount);
	// log.info("----s1----{}", s1);
	// log.info("----s2----{}", s2);
	// log.info("----s3----{}", s3);
	// log.info("----s4----{}", s4);
	// if (acInScore <= 0) {
	// dbscore.setEffctiveScore(Math.floor(s1.subtract(s2).doubleValue()));
	// } else {
	// if (acWaitInScore >= 0) {
	// dbscore.setEffctiveScore(Math.floor(s4.subtract(s3).doubleValue()) > 0 ? 0 :
	// Math.floor(s1.subtract(s2).doubleValue()));
	// dbscore.setNoeffctiveScore(Math.floor(s4.subtract(s3).doubleValue()) > 0 ?
	// Math.floor(s4.subtract(s3).doubleValue()) : 0.00);
	// }
	// }
	// dbscore.setStatisticTime(date);
	// scoreDao.save(dbscore);
	// }
	// return inToOutList;
	// }

	// 公共扣减方法
	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public List<TbSpScoreLogIn> outScore(String type, String userCode, Double amount, String reason, String policyNo) {

		List<TbSpScoreLogIn> inToOutList = Lists.newArrayList();
		TbSpUser user = userDao.findByUserCode(userCode);
		// 积分总额-时间排序
		List<TbSpScoreLogIn> allin = scoreLogInDao.findAllEffect(userCode);
		Double score = 0.00;
		for (TbSpScoreLogIn in : allin) {
			// score += in.getBalance();
			BigDecimal s1 = new BigDecimal(score);
			BigDecimal s2 = new BigDecimal(in.getBalance());
			score = Math.floor(s1.add(s2).doubleValue());
			log.info("积分总额score{}", score.toString());
		}
		Double acInScore = amount;
		Double outScore = 0.00;
		Date date = null;
		for (int i = 0; i < allin.size(); i++) {
			Double balance = allin.get(i).getBalance();
			log.info(balance.toString());
			log.info(acInScore.toString());
			log.info(outScore.toString());
			if (outScore >= amount) {
				break;
			}
			TbSpScoreLogIn newin = new TbSpScoreLogIn();
			try {
				BeanUtilExt.copyProperties(newin, allin.get(i));
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}

			BigDecimal s1 = new BigDecimal(balance);
			BigDecimal s2 = new BigDecimal(acInScore);
			BigDecimal s3 = new BigDecimal(outScore);
			if (balance >= acInScore) {// 足以扣减
				allin.get(i).setBalance(Math.floor(s1.subtract(s2).doubleValue()));
				newin.setBalance(acInScore);
				inToOutList.add(newin);
				scoreLogInDao.save(allin.get(i));
				acInScore = 0.00;
				outScore = amount;
				break;
			} else if (balance < acInScore) {// 不足以扣减
				allin.get(i).setBalance(0.00);
				newin.setBalance(balance);
				inToOutList.add(newin);
				scoreLogInDao.save(allin.get(i));
				// 递减
				acInScore = Math.floor(s2.subtract(s1).doubleValue());
				outScore = Math.floor(s3.add(s1).doubleValue());
			}
		}
		log.info("-----返回条数{}", inToOutList.size());
		log.info("-----生效扣完之后还剩余{}没扣，--记录差额。", acInScore);
		Double acWaitInScore = acInScore;
		if (acWaitInScore > 0) {// 生效扣完之后还是不足，则记录一条退保差额扣减
			TbSpScoreLogOut out = new TbSpScoreLogOut();
			if (type.equals(Constants.CHANGE_TYYPE_TB)) {
				out.setChangeType(Constants.CHANGE_TYYPE_TBBalance);
			} else {
				out.setChangeType(Constants.CHANGE_TYYPE_REDUBalance);
			}
			out.setReChangeScore(Math.floor(acWaitInScore * (-1)));
			out.setAcChangeScore(Math.floor(acWaitInScore * (-1)));
			out.setReason("差额");
			date = new Date();// 取时间
			out.setChangeTime(date);
			out.setGranter("system");
			out.setEffictiveDate(date);
			out.setInvalidDate(date);
			out.setStatus(Constants.TRUE);
			out.setPolicyNo(policyNo);
			out.setReasonNo(policyNo);
			out.setUserCode(userCode);
			out.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
			out.setOpenId(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
			out.setRemark("差额");
			scoreLogOutDao.save(out);

		}
		// 记录扣减
		TbSpScoreLogOut out = new TbSpScoreLogOut();
		if (type.equals(Constants.DIRECT_FRIEND_ISSUE)) {
			out.setChangeType(Constants.DIRECT_FRIEND_TB);
		} else if (type.equals(Constants.INDIRECT_FRIEND_ISSUE)) {
			out.setChangeType(Constants.INDIRECT_FRIEND_TB);
		} else if (type.equals(Constants.CHANNEL_ISSUE)) {
			out.setChangeType(Constants.CHANNEL_TB);
		} else {
			out.setChangeType(type);
		}
		out.setReChangeScore(Math.floor((amount - acInScore) * (-1)));
		out.setAcChangeScore(Math.floor((amount - acInScore) * (-1)));
		out.setReason(reason);
		date = new Date();// 取时间
		out.setChangeTime(date);
		out.setGranter("system");
		out.setEffictiveDate(date);
		out.setInvalidDate(date);
		out.setStatus(Constants.TRUE);
		out.setReasonNo(policyNo);
		out.setPolicyNo(policyNo);
		out.setUserCode(userCode);
		out.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
		out.setOpenId(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
		out.setRemark(reason);
		scoreLogOutDao.save(out);
		// 客户积分总表
		TbSpScore dbscore = scoreDao.findByUserCode(userCode).get(0);
		if (null != dbscore) {
			BigDecimal s1 = new BigDecimal(dbscore.getEffctiveScore());
			BigDecimal s2 = new BigDecimal(amount);// 扣减已生效额度
			log.info("----s1----{}", s1);
			log.info("----s2----{}", s2);
			dbscore.setEffctiveScore(Math.floor(s1.subtract(s2).doubleValue()));
			dbscore.setStatisticTime(date);
		} else {
			// 新增记录
			dbscore = new TbSpScore();
			dbscore.setUserCode(userCode);
			dbscore.setEffctiveScore(Math.floor(amount * (-1)));
			dbscore.setNoeffctiveScore(0.00);
			dbscore.setStatisticTime(new Date());
			dbscore.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
			dbscore.setPhoneNo(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
			dbscore.setSumScore(Math.floor(amount * (-1)));
		}
		scoreDao.save(dbscore);
		return inToOutList;
	}

	@Override
	public ServiceResult myScore(String userCode) {
		ServiceResult sr = new ServiceResult();

		Map<String, Object> map = new HashMap<String, Object>();
		TbSpScore myscore = null;
		List<String> ex = null;
		List<String> mouth = null;
		int week = 0;
		int mouthScore = 0;
		try {
			List<TbSpScore> scoreList = scoreDao.findByUserCode(userCode);
			if (CollectionUtils.isNotEmpty(scoreList)) {
				myscore = scoreList.get(0);
				Calendar calendarWeek = new GregorianCalendar();
				calendarWeek.add(Calendar.WEEK_OF_MONTH, -1);
				Date weekFirstday = DateUtil.dateFormat(calendarWeek.getTime());
				log.info("weekFirstday---{}", weekFirstday);
				week = scoreLogInDao.findSumScoreByUCodeAndDate(userCode, weekFirstday);
				Calendar calendmonth = new GregorianCalendar();
				calendmonth.add(Calendar.MONTH, -1);
				Date monthFirstday = DateUtil.dateFormat(calendmonth.getTime());
				log.info("monthFirstday---{}", monthFirstday);
				mouthScore = scoreLogInDao.findSumScoreByUCodeAndDate(userCode, monthFirstday);
				mouth = scoreLogInDao.findByUCodeAndDate(userCode, monthFirstday);
				List<TbSpScoreLogOut> expire = scoreLogOutDao.findByUCodeAndType(userCode,
						Constants.CHANGE_TYYPE_INVALID);

				if (CollectionUtils.isNotEmpty(expire)) {
					ex = scoreLogOutDao.findExpireByUCode(userCode);
					log.info("ex---{}", ex.size());
				} else {
					List<TbSpScoreLogIn> efin = scoreLogInDao.findAllEffect(userCode);
					if (CollectionUtils.isNotEmpty(efin)) {
						List<String> exi = scoreLogInDao.findNearExpireByUCode(userCode);
						ex = exi;
					} else {
						List<TbSpScoreLogIn> efwaitin = scoreLogInDao.findAllWaitEffect(userCode);
						if (CollectionUtils.isNotEmpty(efwaitin)) {
							List<String> exi = scoreLogInDao.findNearExpireWByUCode(userCode);
							ex = exi;
						}
					}
				}
			}
			map.put("myscore", myscore);// 宝豆余额和累计奖励个数
			map.put("expire", ex);// 最邻近到期时间的一笔
			map.put("mouthList", mouth);// 近一个月奖励明细(图表)
			map.put("weekSum", week);// 近一周奖励
			map.put("mouthSum", mouthScore);// 近一个月奖励
			sr.setResult(map);
		} catch (Exception e) {
			log.error("我的积分请求失败：{}", e);
			sr.setFail();
			sr.setResult("我的积分请求失败!");
		}
		return sr;
	}

	@Override
	public ServiceResult scoreDetail(String userCode, String type, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		int num = (pageNumber - 1) * pageSize;
		if ("all".equals(type)) {
			// List<ScoreDetail> allinout = scoreLogInDao.findAllInAndOut(userCode);
			List<String> allinout = scoreLogInDao.findAllInAndOut(userCode, num, pageSize);
			sr.setResult(allinout);
		}
		if ("in".equals(type)) {
			List<String> allin = scoreLogInDao.findAllIn(userCode, num, pageSize);
			sr.setResult(allin);
		}
		if ("out".equals(type)) {
			List<String> allout = scoreLogOutDao.findAllOut(userCode, num, pageSize);
			sr.setResult(allout);
		}
		return sr;
	}

	@Override
	public TbSpScoreLogOut outInvalidScore(TbSpScoreLogIn orderin, String remark) {

		orderin.setAcChangeScore(orderin.getReChangeScore());
		scoreLogInDao.save(orderin);
		// 记录扣减
		TbSpScoreLogOut out = new TbSpScoreLogOut();
		if (orderin.getChangeType().equals(Constants.DIRECT_FRIEND_ISSUE)) {
			out.setChangeType(Constants.DIRECT_FRIEND_TB);
		} else if (orderin.getChangeType().equals(Constants.INDIRECT_FRIEND_ISSUE)) {
			out.setChangeType(Constants.INDIRECT_FRIEND_TB);
		} else if (orderin.getChangeType().equals(Constants.CHANNEL_ISSUE)) {
			out.setChangeType(Constants.CHANNEL_TB);
		} else {
			out.setChangeType(Constants.CHANGE_TYYPE_TB);
		}
		out.setReChangeScore(orderin.getReChangeScore() * (-1));
		out.setAcChangeScore(orderin.getReChangeScore() * (-1));
		out.setReason(remark);
		out.setChangeTime(new Date());
		out.setGranter("system");
		out.setEffictiveDate(new Date());
		out.setInvalidDate(new Date());
		out.setStatus(Constants.TRUE);
		out.setReasonNo(orderin.getPolicyNo());
		out.setPolicyNo(orderin.getPolicyNo());
		out.setUserCode(orderin.getUserCode());
		out.setTelephone(orderin.getTelephone());
		out.setOpenId(orderin.getOpenid());
		out.setRemark(remark);
		TbSpScoreLogOut dbout = scoreLogOutDao.save(out);
		TbSpScore dbscore = scoreDao.findByUserCode(orderin.getUserCode()).get(0);
		dbscore.setNoeffctiveScore(dbscore.getNoeffctiveScore() - orderin.getReChangeScore());
		scoreDao.save(dbscore);
		return dbout;
	}

	@Override
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public ServiceResult cash(String userCode, double score, String branchCode, String bankNumber, Integer bankId) {

		ServiceResult sr = new ServiceResult();
		sr.setFail();
		if (StringUtils.isBlank(userCode)) {
			sr.setResult("用户信息不能为空！");
			return sr;
		}
		if (score < 100) {
			sr.setResult("提现额度100宝豆起！");
			return sr;
		}
		if (StringUtils.isBlank(bankNumber)) {
			sr.setResult("银行卡号不能为空");
			return sr;
		}
		TbSpBank bank = null;
		if (bankId > 0) {
			bank = bankDao.findBankById(bankId);// 查询该银行卡
		}
		if (null == bank) {
			List<TbSpBank> bankList = bankDao.findDefaultBankByUserCode(userCode, userCode);
			if (CollectionUtils.isEmpty(bankList)) {
				sr.setResult("无默认银行卡信息,请设置！");
				return sr;
			}
			bank = bankList.get(0);
		}
		// 校验是否需是本人注册的银行卡
		if (!(userCode.equals(bank.getUserCode()) && bankNumber.equals(bank.getNumber()))) {
			sr.setResult("非法请求：银行账号被非法修改");
			return sr;
		}
		// 校验
		if (StringUtil.isEmpty(bank.getIdNumber()) || StringUtil.isEmpty(bank.getUserName())
				|| StringUtil.isEmpty(bank.getNumber()) || StringUtil.isEmpty(bank.getMobile())
				|| StringUtil.isEmpty(bank.getFullName()) || StringUtil.isEmpty(bank.getBranchName())) {
			sr.setResult("请完善银行卡信息！");
			return sr;
		}
		List<TbSpScore> scoreList = scoreDao.findByUserCode(userCode);
		if (CollectionUtils.isEmpty(scoreList)) {
			sr.setResult("该用户无积分纪录");
			return sr;
		}
		TbSpScore spScore = scoreList.get(0);
		double balance = spScore.getEffctiveScore();
		if (score > balance) {
			sr.setResult("非法请求：余额不足");
			return sr;
		}
		TbSpUser user = userDao.findByUserCode(userCode);
		// 获取兑换比例
		// double cash = score / 500;
		double rate = scoreConfigDao.findAllConfig().get(0).getRate();
		BigDecimal b1 = new BigDecimal(score);
		BigDecimal b2 = new BigDecimal(rate);
		double cash = b1.divide(b2).setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		log.info("--------提现额度：{}", cash);
		// 请求 epayment 积分体现
		Epayment payment = new Epayment();
		payment.setPayType("online");
		payment.setBusinessSource("cnp");
		payment.setPlatformId("bill-cnp");
		payment.setRemarks("销售平台积分提现");
		/*
		 * if(StringUtil.isNotEmpty(branchCode)){
		 * if("3399".equals(branchCode.substring(0,4))){
		 * branchCode=branchCode.substring(0,4); }else{
		 * branchCode=branchCode.substring(0,2); } payment.setBranchCode(branchCode); }
		 */
		payment.setBranchCode("00");// 现在只有一个总公司的商户号，固定传00
		payment.setProperty00(bank.getMobile());
		payment.setProperty01(bank.getNumber());// 卡号
		payment.setProperty02(bank.getUserName());
		payment.setProperty03(bank.getIdNumber());
		payment.setProperty04(bank.getFullName());
		payment.setProperty05(bank.getBranchName());
		payment.setProperty06(StringUtils.isBlank(bank.getProvince()) ? "" : bank.getProvince());// 开户行省份
		payment.setProperty07(StringUtils.isBlank(bank.getCity()) ? "" : bank.getCity());// 开户行城市
		payment.setProperty08(StringUtils.isBlank(bank.getArea()) ? "" : bank.getArea());// 开户行区
		// test

		/*
		 * payment.setAmount("100.00"); payment.setProperty00("15683798990");
		 * payment.setProperty01("6214830231555326"); payment.setProperty02("王开发");
		 * payment.setProperty03("500243198808082914"); payment.setProperty04("招商银行");
		 * payment.setProperty05("招商银行重庆分行"); payment.setProperty06("重庆市");
		 * payment.setProperty07("重庆");
		 */

		DecimalFormat df = new DecimalFormat("0.00");
		String amountStr = df.format(cash);
		payment.setAmount(amountStr);// 金额（小数，单位为元，格式：xxxx.xx）
		String businessNo = userCode + DateUtil.dateFromat(new Date(), DateUtil.DATE_TIME_PATTERN3)
				+ new Date().getTime();
		payment.setBusinessNo(businessNo);
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.EPAYMENT_CASH_URL.getUrlKey());
		if (null == sysServiceInfo) {
			sr.setResult("未获取到请求地址,请检查配置");
			return sr;
		}
		String key = sysServiceInfo.getTocken();
		// String key="v56878yb9s6dwghm99999bc3tvp6abbb";
		String parm = this.cashParameter(payment, key);
		if (StringUtils.isEmpty(parm)) {
			sr.setResult("生成密钥失败,请检查配置");
			return sr;
		}

		TbSpSaleLog saleLog = new TbSpSaleLog();

		try {
			// String rs = HttpAndHttpsUtil.httpPost(sysServiceInfo.getUrl(), parm,
			// "UTF-8");
			String url = sysServiceInfo.getUrl();
			saleLog.setRequestData(parm);
			saleLog.setRequestTime(new Date());
			saleLog.setUserCode(userCode);
			saleLog.setOperation("提现");
			saleLog.setMark(businessNo);
			/**
			 * 请求MQ
			 */
			MessageDto reqeust = new MessageDto();
			Map mqmap = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
			SysServiceInfo s = (SysServiceInfo) mqmap.get(CoreServiceEnum.MQ_CASH_URL.getUrlKey());
			/*
			 * s.setUrl(
			 * "http://10.132.28.243:28008/mq/SaleplatformGroup/saleplatSystem/send");
			 * s.setUserName("saleplat"); s.setPassword("368a049c73609c45ce01609c45ce9c00");
			 */

			reqeust.setKey(s.getUserName() + DateUtil.dateFromat(new Date(), DateUtil.DATE_TIME_PATTERN3)
					+ new Date().getTime());
			reqeust.setTopic("SCORE");
			reqeust.setTag("WITHDRAWAL");
			JSONObject body = new JSONObject();
			body.put("url", url);
			body.put("param", parm);
			body.put("businessNo", businessNo);
			reqeust.setBody(body);
			HttpEntity<MessageDto> requestEntity = new HttpEntity<MessageDto>(reqeust,
					RequestUtils.genMQHttpHeaders(s.getUserName(), s.getPassword()));
			log.info("MQ请求epayment报文{}", JSONObject.toJSONString(reqeust));
			cn.com.libertymutual.sp.mq.ServiceResult mqReponse = restTemplate.postForObject(s.getUrl(), requestEntity,
					cn.com.libertymutual.sp.mq.ServiceResult.class);
			log.info("MQ返回报文{}", JSONObject.toJSONString(mqReponse));
			saleLog.setResponseData(JSONObject.toJSONString(mqReponse));
			String status = "1";
			List<TbSpScoreLogIn> inToOutList = null;
			if (null != mqReponse && ResponseStatus.OK.getResponseStatus().equals(mqReponse.getStatus())) {
				// scoreDao.reduceScore(score, userCode);

				inToOutList = this.outScore(Constants.CHANGE_TYYPE_CASH, userCode, score, "提现",
						payment.getBusinessNo());
				log.info("---=======inToOutList size============----{}", inToOutList.size());
				sr.setSuccess();
				status = "2";// 处理中
				sr.setResult(JSONObject.toJSONString(mqReponse));
				cashLog(inToOutList, payment, bank, userCode, score, cash, rate, status,
						null != mqReponse ? mqReponse.getMessage() : "");
			} else {
				status = "1";
				sr.setFail();// MQ请求失败
				sr.setResult("提现失败！");
			}

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			spSaleLogDao.save(saleLog);
		}

		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRES_NEW)
	public String cashLog(List<TbSpScoreLogIn> inToOutList, Epayment payment, TbSpBank bank, String userCode,
			double score, double cash, double rate, String status, String message) {

		TbSpUser user = userDao.findByUserCode(userCode);
		TbSpCashLog cashLog = new TbSpCashLog(payment.getBusinessNo(),
				StringUtils.isNotBlank(user.getMobile()) ? user.getMobile() : "", userCode, score, cash, status,
				new Date(), "CNY", rate, bank.getUserName(), bank.getIdNumber(), bank.getFullName(), bank.getNumber(),
				bank.getBranchName(), bank.getProvince(), bank.getCity(), payment.getProperty00(),
				payment.getBranchCode(), message);

		cashLogDao.save(cashLog);
		// 提现明细记录
		if (CollectionUtils.isNotEmpty(inToOutList)) {
			for (TbSpScoreLogIn in : inToOutList) {
				log.info("---=in.getPolicyNo()==================----{}", in.getPolicyNo());
				log.info("---=in.getReasonNo()==================----{}", in.getReasonNo());
				log.info("---=in.getBranchCode()==================----{}", in.getBranchCode());
				TbSpCashDetail detail = new TbSpCashDetail(payment.getBusinessNo(), in.getBalance(),
						(double) (Math.round((in.getBalance() / rate) * 100) / 100.0), rate, new Date(),
						in.getChangeType(), "CNY", in.getPolicyNo(), in.getReasonNo(), in.getReason(), in.getRemark(),
						in.getBranchCode());
				cashDetailDao.save(detail);
			}
		}

		return status;

	}

	@Override
	public ServiceResult cashPatch(String businessNo, String branchCode, Integer bankId) {
		ServiceResult sr = new ServiceResult();
		sr.setFail();
		List<TbSpCashLog> logs = cashLogDao.findFailBybusinessNo(businessNo);
		if (logs == null || logs.size() == 0) {
			sr.setResult("无记录或非失败状态！");
			return sr;
		}
		TbSpCashLog cashLog = logs.get(0);
		TbSpBank bank = null;
		if (bankId > 0) {
			bank = bankDao.findBankById(bankId);// 查询该银行卡
		}
		if (null == bank) {
			List<TbSpBank> bankList = bankDao.findDefaultBankByUserCode(cashLog.getUserCode(), cashLog.getUserCode());
			if (CollectionUtils.isEmpty(bankList)) {
				sr.setResult("无默认银行卡信息,请设置！");
				return sr;
			}
			bank = bankList.get(0);
		}
		Epayment payment = new Epayment();
		payment.setPayType("online");
		payment.setBusinessSource("cnp");
		payment.setPlatformId("bill-cnp");
		payment.setRemarks("销售平台积分提现");
		payment.setBranchCode(cashLog.getBranchCode());
		payment.setProperty00(bank.getMobile());
		payment.setProperty01(bank.getNumber());// 卡号
		payment.setProperty02(bank.getUserName());
		payment.setProperty03(bank.getIdNumber());
		payment.setProperty04(bank.getFullName());
		payment.setProperty05(bank.getBranchName());
		payment.setProperty06(StringUtils.isBlank(bank.getProvince()) ? "" : bank.getProvince());// 开户行省份
		payment.setProperty07(StringUtils.isBlank(bank.getCity()) ? "" : bank.getCity());// 开户行城市
		payment.setProperty08(StringUtils.isBlank(bank.getArea()) ? "" : bank.getArea());// 开户行区

		DecimalFormat df = new DecimalFormat("0.00");
		String amountStr = df.format(cashLog.getMoney());
		payment.setAmount(amountStr);// 金额（小数，单位为元，格式：xxxx.xx）
		payment.setBusinessNo(businessNo);
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.EPAYMENT_CASH_URL.getUrlKey());
		if (null == sysServiceInfo) {
			sr.setResult("未获取到请求地址,请检查配置");
			return sr;
		}
		String key = sysServiceInfo.getTocken();
		// String key="v56878yb9s6dwghm99999bc3tvp6abbb";
		String parm = this.cashParameter(payment, key);
		if (StringUtils.isEmpty(parm)) {
			sr.setResult("生成密钥失败,请检查配置");
			return sr;
		}

		TbSpSaleLog saleLog = new TbSpSaleLog();

		try {
			String url = sysServiceInfo.getUrl();
			saleLog.setRequestData(parm);
			saleLog.setRequestTime(new Date());
			saleLog.setUserCode(Current.userId.get());
			saleLog.setOperation("提现");
			/**
			 * 请求MQ
			 */
			MessageDto reqeust = new MessageDto();
			Map mqmap = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
			SysServiceInfo s = (SysServiceInfo) mqmap.get(CoreServiceEnum.MQ_CASH_URL.getUrlKey());

			reqeust.setKey(s.getUserName() + DateUtil.dateFromat(new Date(), DateUtil.DATE_TIME_PATTERN3)
					+ new Date().getTime());
			reqeust.setTopic("SCORE");
			reqeust.setTag("WITHDRAWAL");
			JSONObject body = new JSONObject();
			body.put("url", url);
			body.put("param", parm);
			body.put("businessNo", businessNo);
			reqeust.setBody(body);
			HttpEntity<MessageDto> requestEntity = new HttpEntity<MessageDto>(reqeust,
					RequestUtils.genMQHttpHeaders(s.getUserName(), s.getPassword()));
			log.info("MQ请求epayment报文{}", JSONObject.toJSONString(reqeust));
			cn.com.libertymutual.sp.mq.ServiceResult mqReponse = restTemplate.postForObject(s.getUrl(), requestEntity,
					cn.com.libertymutual.sp.mq.ServiceResult.class);
			log.info("MQ返回报文{}", JSONObject.toJSONString(mqReponse));
			saleLog.setResponseData(JSONObject.toJSONString(mqReponse));
			saleLog.setMark(businessNo);
			cashLog.setIdcard(bank.getIdNumber());
			cashLog.setPayeeAccount(bank.getNumber());
			cashLog.setPayee(bank.getUserName());
			cashLog.setPhoneNo(bank.getMobile());
			cashLog.setStatus("2");
			cashLog.setBankCity(bank.getCity());
			cashLog.setBankProvence(bank.getProvince());
			cashLog.setBankName(bank.getBranchName());
			cashLog.setPayeeBank(bank.getFullName());
			cashLog.setPayeePhone(payment.getProperty00());
			cashLog.setRemarks("提现补录");
			cashLog.setUpdateTime(new Date());
			cashLogDao.save(cashLog);
			sr.setSuccess();
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		} finally {
			spSaleLogDao.save(saleLog);
		}
		return sr;
	}

	public String cashParameter(Epayment payment, String key) {
		if (null == payment) {
			return "";
		}

		/*** 构建参数串 ***/
		String parameter = "";
		try {
			Object obj = payment;
			Class cls = obj.getClass();
			Field[] fields = cls.getDeclaredFields();
			for (Field field : fields) {
				if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
					continue;
				}
				field.setAccessible(true);
				String propertieNameString = field.toString().substring(field.toString().lastIndexOf(".") + 1);
				Object value = field.get(obj);
				/// if (!(value == "") && !(value == null)) {
				if (value != null && value.toString().length() > 0) {
					parameter += propertieNameString + "=" + value + "&";
				}
			}
			parameter = InsureUtils.sortByName(parameter);// 排序/*parameter = encode(parameter);//转码 */
			String securityCode = InsureUtils.encodeByMD5(parameter + key);// 加密 // Tocken is key
			parameter += "&securityCode=" + securityCode;

			payment.setSecurityCode(securityCode);

			return parameter;

		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}

		return "";
	}

	@Override
	public ServiceResult cashLog(String comCode, String startDate, String endDate, String status, String userCode,
			String mobile, String businessNo, int pageNumber, int pageSize) {

		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");

		Page<TbSpCashLog> page = cashLogDao.findAll(new Specification<TbSpCashLog>() {
			public Predicate toPredicate(Root<TbSpCashLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();

				if (StringUtils.isNotEmpty(comCode)) {
					log.info(comCode);
					if (!"00000000".equals(comCode)) {
						if (!comCode.startsWith("WX") && !comCode.startsWith("BS")) {
							log.info(comCode.substring(0, 4));
							List<TbSpUser> users = userDao.findByBranchCode(comCode.substring(0, 4));
							if (CollectionUtils.isNotEmpty(users)) {
								In<String> in = cb.in(root.get("userCode").as(String.class));
								for (TbSpUser u : users) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(u.getUserCode());
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
										in.value(userCodeBs);
									}
									in.value(u.getUserCode());
								}
								predicate.add(in);
							} else {
								predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
							}
						} else {
							Set<String> newList = new HashSet();
							List<TbSpUser> users = userDao.findByComCode(comCode);
							if (CollectionUtils.isNotEmpty(users)) {
								for (TbSpUser u : users) {
									newList.add(u.getUserCode());
								}
							}
							log.info("----newList----{}", newList.toString());
							Set<String> allcom = new HashSet();
							allcom = levelService.findAllNextBranchNo(newList, allcom);
							log.info("----allcom----{}", allcom.toString());
							allcom.add(comCode);
							allcom.addAll(newList);
							log.info("----allcom----{}", allcom.toString());
							if (CollectionUtils.isNotEmpty(allcom)) {
								In<String> in = cb.in(root.get("userCode").as(String.class));
								for (String ts : allcom) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(ts);
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
										in.value(userCodeBs);
									}
									in.value(ts);
								}
								predicate.add(in);
							} else {
								predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
							}
						}
					}
				}

				if (StringUtils.isNotBlank(startDate)) {
					log.info(startDate);
					predicate.add(cb.greaterThanOrEqualTo(root.get("createTime").as(String.class), startDate));
				}
				if (StringUtils.isNotBlank(endDate)) {
					log.info(endDate);
					predicate.add(cb.lessThanOrEqualTo(root.get("createTime").as(String.class), endDate));
				}
				if (StringUtils.isNotBlank(userCode)) {
					log.info(userCode);
					predicate.add(cb.equal(root.get("userCode").as(String.class), userCode));
				}
				if (StringUtils.isNotBlank(mobile)) {
					log.info(mobile);
					predicate.add(cb.like(root.get("phoneNo").as(String.class), "%" + mobile + "%"));
				}
				if (StringUtils.isNotBlank(status)) {
					log.info(status);
					predicate.add(cb.equal(root.get("status").as(String.class), status));
				}
				if (StringUtils.isNotBlank(businessNo)) {
					log.info(businessNo);
					predicate.add(cb.like(root.get("businessNo").as(String.class), "%" + businessNo + "%"));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));

		sr.setResult(page);
		return sr;
	}

	@Override
	public ServiceResult scoreConfig() {
		ServiceResult sr = new ServiceResult();
		List<TbSpScoreConfig> scoreconfig = null;
		List<TbSpScoreConfig> redisscoreconfig = (List<TbSpScoreConfig>) redisUtils.get(Constants.SCORE_CONFIG_INFO);
		if (CollectionUtils.isNotEmpty(redisscoreconfig)) {
			scoreconfig = redisscoreconfig;
		} else {
			scoreconfig = scoreConfigDao.findAllConfig();
			redisUtils.set(Constants.SCORE_CONFIG_INFO, scoreconfig);
		}
		sr.setResult(scoreconfig);
		return sr;
	}

	@Override
	public ServiceResult updateScoreConfig(TbSpScoreConfig scoreConfig) {
		ServiceResult sr = new ServiceResult();
		if (null != scoreConfig.getId()) {

			List<TbSpScoreConfig> dbscoreconfig = scoreConfigDao.findAllConfig();
			if (scoreConfig.getRate() != dbscoreconfig.get(0).getRate()
					&& !scoreConfig.getRate().equals(dbscoreconfig.get(0).getRate())) {
				sr.setFail();
				sr.setResult("不可修改积分兑换比例！");
				return sr;
			}
			sr.setResult(scoreConfigDao.save(scoreConfig));
			List<TbSpScoreConfig> scoreconfig = scoreConfigDao.findAllConfig();
			redisUtils.set(Constants.SCORE_CONFIG_INFO, scoreconfig);
		}
		return sr;
	}

	@Override
	public ServiceResult userScore(String comCode, String startDate, String endDate, String userCode, String mobile,
			int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");
		Page<TbSpScore> page = scoreDao.findAll(new Specification<TbSpScore>() {
			public Predicate toPredicate(Root<TbSpScore> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();

				if (StringUtils.isNotEmpty(comCode)) {
					log.info(comCode);
					if (!"00000000".equals(comCode)) {
						if (!comCode.startsWith("WX") && !comCode.startsWith("BS")) {
							log.info(comCode.substring(0, 4));
							List<TbSpUser> users = userDao.findByBranchCode(comCode.substring(0, 4));
							if (CollectionUtils.isNotEmpty(users)) {
								In<String> in = cb.in(root.get("userCode").as(String.class));
								for (TbSpUser u : users) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(u.getUserCode());
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
										in.value(userCodeBs);
									}
									in.value(u.getUserCode());
								}
								predicate.add(in);
							} else {
								predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
							}
						} else {
							Set<String> newList = new HashSet();
							List<TbSpUser> users = userDao.findByComCode(comCode);
							if (CollectionUtils.isNotEmpty(users)) {
								for (TbSpUser u : users) {
									newList.add(u.getUserCode());
								}
							}
							log.info("----newList----{}", newList.toString());
							Set<String> allcom = new HashSet();
							allcom = levelService.findAllNextBranchNo(newList, allcom);
							log.info("----allcom----{}", allcom.toString());
							allcom.add(comCode);
							allcom.addAll(newList);
							log.info("----allcom----{}", allcom.toString());
							if (CollectionUtils.isNotEmpty(allcom)) {
								In<String> in = cb.in(root.get("userCode").as(String.class));
								for (String ts : allcom) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(ts);
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
										in.value(userCodeBs);
									}
									in.value(ts);
								}
								predicate.add(in);
							} else {
								predicate.add(cb.equal(root.get("userCode").as(String.class), "LL"));
							}
						}
					}
				}

				if (StringUtils.isNotEmpty(startDate)) {
					log.info(startDate);
					predicate.add(cb.greaterThanOrEqualTo(root.get("statisticTime").as(String.class), startDate));
				}
				if (StringUtils.isNotEmpty(endDate)) {
					log.info(endDate);
					predicate.add(cb.lessThanOrEqualTo(root.get("statisticTime").as(String.class), endDate));
				}
				if (StringUtils.isNotEmpty(userCode)) {
					log.info(userCode);
					predicate.add(cb.equal(root.get("userCode").as(String.class), userCode));
				}
				if (StringUtils.isNotEmpty(mobile)) {
					log.info(mobile);
					predicate.add(cb.like(root.get("phoneNo").as(String.class), "%" + mobile + "%"));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));

		sr.setResult(page);
		return sr;
	}

	@Override
	public ServiceResult findIntegralDetail(String type, Integer id) {
		ServiceResult sr = new ServiceResult();
		if ("in".equals(type)) {
			sr.setResult(scoreLogInDao.findById(id).get());
		} else if ("out".equals(type)) {
			sr.setResult(scoreLogOutDao.findById(id).get());
		}
		return sr;
	}

	/**
	 * 快钱交易查询
	 */
	@Override
	public ServiceResult queryCnp(String businessNo, String branchCode, String startDate, String endDate,
			int pageNumber, int pageSize) {
		ServiceResult rs = new ServiceResult();
		rs.setFail();
		if (StringUtils.isEmpty(businessNo) && (StringUtils.isEmpty(branchCode) || StringUtils.isEmpty(startDate)
				|| StringUtils.isEmpty(endDate))) {
			rs.setResult("请求参数不能为空！");
			return rs;
		}
		Map map = (Map) redisUtils.get(Constants.SYS_SERVICE_INFO);
		SysServiceInfo sysServiceInfo = (SysServiceInfo) map.get(CoreServiceEnum.EPAYMENT_QUERYCNP_URL.getUrlKey());
		if (null == sysServiceInfo) {
			rs.setResult("未获取到请求地址,请检查配置");
			return rs;
		}
		String key = sysServiceInfo.getTocken();
		StringBuilder param = new StringBuilder();
		if (StringUtil.isNotEmpty(businessNo)) {
			param.append("businessNo=").append(businessNo).append("&businessSource=cnp").append("&property00=")
					.append(pageNumber).append("&property01=").append(pageSize);
		} else if (StringUtils.isNotEmpty(branchCode) && StringUtils.isNotEmpty(startDate)
				&& StringUtils.isNotEmpty(endDate)) {
			if (branchCode.indexOf("3399") < 0) {
				branchCode = branchCode.substring(0, 2);
			}
			param.append("branchCode=").append(branchCode).append("&businessSource=cnp").append("&property00=")
					.append(pageNumber).append("&property01=").append(pageSize).append("&property02=").append(startDate)
					.append("&property03=").append(endDate);
		}
		String parameter = InsureUtils.sortByName(param.toString());// 排序/*parameter = encode(parameter);//转码 */
		String securityCode = InsureUtils.encodeByMD5(parameter + key);// 加密 // Tocken is key
		parameter += "&securityCode=" + securityCode;

		try {
			String responseStr = restTemplate
					.exchange(sysServiceInfo.getUrl() + "?" + parameter, HttpMethod.POST, null, String.class).getBody();
			// responseStr="<?xml version=\"1.0\" encoding=\"UTF-8\"
			// standalone=\"yes\"?><MasMessage
			// xmlns=\"http://www.99bill.com/mas_cnp_merchant_interface\"><version>1.0</version><BatchQryWithPayOrderMsgContent><txnTotal>1</txnTotal><TxnListCount>1</TxnListCount><WithPayOrderListContent><WithPayOrder><merchantId>812333245110002</merchantId><externalRefNumber>WX00000023201801161516072297830</externalRefNumber><orderType>03</orderType><entryChannel>02</entryChannel><amount>0</amount><pointAmt>100</pointAmt><phoneNO>18628117775</phoneNO><cardHolderName>吴娅</cardHolderName><cardHolderId>510107197605040868</cardHolderId><bankName>中国银行</bankName><openBankName>建设银行成都市支行</openBankName><openCardProvince>四川省</openCardProvince><openCardCity>成都市</openCardCity><voucherNo>7240201801161117284038465</voucherNo><mamMembercode>24000010600</mamMembercode><subStatus>0070</subStatus><mainStatus>F</mainStatus></WithPayOrder></WithPayOrderListContent></BatchQryWithPayOrderMsgContent></MasMessage>";
			log.info(responseStr);
			if (StringUtil.isNotEmpty(responseStr) && responseStr.startsWith("<?xml")) {

				XmlBinder<BatchQryWithPayOrderMsgContent> binder = new XmlBinder<BatchQryWithPayOrderMsgContent>(
						BatchQryWithPayOrderMsgContent.class);
				binder.getDocument(responseStr);
				BatchQryWithPayOrderMsgContent epaymentOsf = binder.getElementObject(
						"/MasMessage/BatchQryWithPayOrderMsgContent", BatchQryWithPayOrderMsgContent.class);
				rs.setResult(epaymentOsf);
				rs.setSuccess();
			} else {
				rs.setAppFail();
				rs.setResult(responseStr);
			}
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			rs.setAppFail();
			rs.setResult(e.getMessage());
		}
		return rs;
	}

	@Override
	public ServiceResult drawLogList(String startDate, String endDate, String status, String policyNo, String mobile,
			String userCode, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		List<Order> orders = new ArrayList<Order>();
		orders.add(new Order(Direction.DESC, "status"));
		orders.add(new Order(Direction.DESC, "id"));
		/// Sort sort = new Sort(orders);
		Sort sort = Sort.by(orders);
		Page<TbSpDrawLog> page = drawLogDao.findAll(new Specification<TbSpDrawLog>() {
			public Predicate toPredicate(Root<TbSpDrawLog> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(startDate)) {
					log.info(startDate);
					predicate.add(cb.greaterThanOrEqualTo(root.get("drawTime").as(String.class), startDate));
				}
				if (StringUtils.isNotEmpty(endDate)) {
					log.info(endDate);
					predicate.add(cb.lessThanOrEqualTo(root.get("drawTime").as(String.class), endDate));
				}
				if (StringUtils.isNotEmpty(status)) {
					log.info(status);
					predicate.add(cb.equal(root.get("status").as(String.class), status));
				}
				if (StringUtils.isNotEmpty(mobile)) {
					log.info(mobile);
					predicate.add(cb.equal(root.get("telephone").as(String.class), mobile));
				}
				if (StringUtils.isNotEmpty(policyNo)) {
					log.info(status);
					predicate.add(cb.equal(root.get("policyNo").as(String.class), policyNo));
				}
				if (StringUtils.isNotEmpty(userCode)) {
					log.info(userCode);
					String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
					TbSpUser user = userDao.findByUserCode(userCode);
					if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
						userCodeBs = user.getUserCodeBs();
						log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
								user.getUserCodeBs());
					}
					predicate.add(cb.or(cb.equal(root.get("userCode").as(String.class), userCode),
							cb.equal(root.get("userCode").as(String.class), userCodeBs)));
				}

				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));
		sr.setResult(page);
		return sr;
	}

	@Override
	public ServiceResult cashToInScoreDetail(String comCode, String startDate, String endDate, String branchCode,
			String userCode, String mobile, int pageNumber, int pageSize) {
		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.DESC, "id");
		Page<TbSpCashDetail> page = cashDetailDao.findAll(new Specification<TbSpCashDetail>() {
			public Predicate toPredicate(Root<TbSpCashDetail> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(comCode)) {
					log.info(comCode);
					if (!"00000000".equals(comCode)) {
						if (!comCode.startsWith("WX") && !comCode.startsWith("BS")) {
							log.info(comCode.substring(0, 4));
							predicate.add(cb.equal(root.get("branchCode").as(String.class), comCode.substring(0, 4)));
						} else {
							Set<String> newList = new HashSet();
							List<TbSpUser> users = userDao.findByComCode(comCode);
							if (CollectionUtils.isNotEmpty(users)) {
								for (TbSpUser u : users) {
									newList.add(u.getUserCode());
								}
							}
							log.info("----newList----{}", newList.toString());
							Set<String> allcom = new HashSet();
							allcom = levelService.findAllNextBranchNo(newList, allcom);
							log.info("----allcom----{}", allcom.toString());
							allcom.add(comCode);
							allcom.addAll(newList);
							log.info("----allcom----{}", allcom.toString());
							if (CollectionUtils.isNotEmpty(allcom)) {
								In<String> in = cb.in(root.get("businessNo").as(String.class));
								for (String ts : allcom) {
									String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
									TbSpUser user = userDao.findByUserCode(ts);
									if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
										userCodeBs = user.getUserCodeBs();
										log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
												user.getUserCodeBs());
									}
									List<TbSpCashLog> cashLog = cashLogDao.findByUserCode(userCode, userCodeBs);
									if (CollectionUtils.isNotEmpty(cashLog)) {
										for (TbSpCashLog tsc : cashLog) {
											in.value(tsc.getBusinessNo());
										}
										predicate.add(in);
									} else {
										predicate.add(cb.equal(root.get("businessNo").as(String.class), userCode));
									}
								}
							} else {
								predicate.add(cb.equal(root.get("businessNo").as(String.class), "LL"));
							}
						}
					}
				} else {
					predicate.add(cb.equal(root.get("businessNo").as(String.class), "LL"));
				}

				if (StringUtils.isNotEmpty(branchCode)) {
					log.info(branchCode);
					predicate.add(cb.equal(root.get("branchCode").as(String.class), branchCode));
				}
				if (StringUtils.isNotEmpty(userCode)) {
					log.info(userCode);
					String userCodeBs = "-";// -表示用户的userCode值在订单的userId字段不可能有该字符
					TbSpUser user = userDao.findByUserCode(userCode);
					if (user != null && StringUtils.isNotBlank(user.getUserCodeBs())) {
						userCodeBs = user.getUserCodeBs();
						log.info("合并的用户[id={},code={}],有codebs值={}", user.getId(), user.getUserCode(),
								user.getUserCodeBs());
					}

					List<TbSpCashLog> cashLog = cashLogDao.findByUserCode(userCode, userCodeBs);
					if (CollectionUtils.isNotEmpty(cashLog)) {
						In<String> in = cb.in(root.get("businessNo").as(String.class));
						for (TbSpCashLog ts : cashLog) {
							in.value(ts.getBusinessNo());
						}
						predicate.add(in);
					} else {
						predicate.add(cb.equal(root.get("businessNo").as(String.class), userCode));
					}
				}
				if (StringUtils.isNotEmpty(mobile)) {
					List<TbSpCashLog> cashLog = cashLogDao.findByMobile(mobile);
					if (CollectionUtils.isNotEmpty(cashLog)) {
						In<String> in = cb.in(root.get("businessNo").as(String.class));
						for (TbSpCashLog ts : cashLog) {
							in.value(ts.getBusinessNo());
						}
						predicate.add(in);
					} else {
						predicate.add(cb.equal(root.get("businessNo").as(String.class), mobile));
					}
				}
				if (StringUtils.isNotEmpty(startDate)) {
					log.info(startDate);
					predicate.add(cb.greaterThanOrEqualTo(root.get("createTime").as(String.class), startDate));
				}
				if (StringUtils.isNotEmpty(endDate)) {
					log.info(endDate);
					predicate.add(cb.lessThanOrEqualTo(root.get("createTime").as(String.class), endDate));
				}
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort));

		List<TbSpCashDetail> list = page.getContent();
		for (TbSpCashDetail detail : list) {
			if (StringUtils.isNotBlank(detail.getPolicyNo())) {
				List<TbSpOrder> orders = orderDao.findByPolicyNo(detail.getPolicyNo());
				if (CollectionUtils.isNotEmpty(orders)) {
					detail.setOrder(orders.get(0));
				}
			}
			TbSpCashLog Log = cashLogDao.findBybusinessNo(detail.getBusinessNo());
			detail.setCashLog(Log);
		}
		sr.setResult(page);
		return sr;
	}

	@Override
	public ServiceResult cashTest(String userCode, Double score, String policyNo) {

		List<TbSpScoreLogIn> ins = (List<TbSpScoreLogIn>) scoreLogInDao.findAll();
		for (TbSpScoreLogIn in : ins) {
			if (StringUtils.isNotBlank(in.getPolicyNo())) {
				String areaCode = in.getPolicyNo().substring(6, 10);
				List<TbSysHotarea> area = tbSysHotareaDao.findLikeBranchCodeLike(areaCode);
				if (CollectionUtils.isNotEmpty(area)) {
					in.setBranchCode(area.get(0).getBranchCode());
					scoreLogInDao.save(in);
				}
			}
		}

		List<TbSpCashDetail> cashd = (List<TbSpCashDetail>) cashDetailDao.findAll();
		for (TbSpCashDetail in : cashd) {
			if (StringUtils.isNotBlank(in.getPolicyNo())) {
				String areaCode = in.getPolicyNo().substring(6, 10);
				List<TbSysHotarea> area = tbSysHotareaDao.findLikeBranchCodeLike(areaCode);
				if (CollectionUtils.isNotEmpty(area)) {
					in.setBranchCode(area.get(0).getBranchCode());
					cashDetailDao.save(in);
				}
			}
		}

		ServiceResult sr = new ServiceResult();
		// List<TbSpScoreLogIn> inToOutList = this.outScore(Constants.CHANGE_TYYPE_CASH,
		// userCode, score, "提现", policyNo);
		// double rate = scoreConfigDao.findAllConfig().get(0).getRate();
		// BigDecimal b1 = new BigDecimal(score);
		// BigDecimal b2 = new BigDecimal(rate);
		// double cash = b1.divide(b2).setScale(2,
		// BigDecimal.ROUND_HALF_UP).doubleValue();
		// log.info("---=======inToOutList size============----{}", inToOutList.size());
		// List<TbSpBank> bankList = bankDao.findDefaultBankByUserCode(userCode,
		// userCode);
		// TbSpBank bank = null;
		// if (CollectionUtils.isEmpty(bankList)) {
		// sr.setResult("无默认银行卡信息,请设置！");
		// return sr;
		// }
		// bank = bankList.get(0);
		// Epayment payment = new Epayment();
		// payment.setBranchCode("00");
		// payment.setAmount("100.00");
		// payment.setProperty00("15215260930");
		// payment.setProperty01("6214830231555326");
		// payment.setProperty02("王开发");
		// payment.setProperty03("500243198808082914");
		// payment.setProperty04("招商银行");
		// payment.setProperty05("招商银行重庆分行");
		// payment.setProperty06("重庆市");
		// payment.setProperty07("重庆");
		// payment.setBusinessNo("WX00000172018020915181563628234");
		// sr.setResult(cashLog(inToOutList, payment, bank, userCode, score, cash, rate,
		// "00", "00"));
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public List<TbSpScoreLogIn> channelInScore(TbSpOrder order, TbSpUser user) {

		List<TbSpScoreLogIn> scoreList = Lists.newArrayList();
		List<TbSpApplicant> applicant = applicantDao.findByOrderNo(order.getOrderNo());
		TbSpSaleLog saleLog = new TbSpSaleLog();
		saleLog.setRequestData(order.toString());
		saleLog.setRequestTime(new Date());
		saleLog.setUserCode(user.getUserCode());
		saleLog.setOperation(saleLog.CHANNEL_SCORE);
		saleLog.setMark(order.getPolicyNo());
		if (CollectionUtils.isNotEmpty(applicant)) {
			for (TbSpApplicant at : applicant) {
				log.info("at.getCarId():{}", at.getCarId());
				if (at.getCarId().equals(user.getIdNumber())) {
					log.info("-----积分用户投保人、被保人是本人不获得积分------{}");
					saleLog.setResponseData("积分用户投保人、被保人是本人不获得积分");
					spSaleLogDao.save(saleLog);
					return scoreList;
				}
			}
		}
		// if (user.getUserType().equals("3") ||user.getUserType().equals("4")) {
		// log.info("-----非积分用户-----{}",user.getUserCode());
		// return scoreList;
		// }
		if (StringUtils.isBlank(user.getIdNumber())) {
			log.info("-----未实名-不获得积分-----");
			saleLog.setResponseData("未实名-不获得积分");
			spSaleLogDao.save(saleLog);
			return scoreList;
		}
		if (Constants.FALSE.equals(user.getStoreFlag())) {
			log.info("-----未开店-不获得积分-----");
			saleLog.setResponseData("未实名-不获得积分");
			spSaleLogDao.save(saleLog);
			return scoreList;
		}
		List<String> userCodes = Lists.newArrayList();
		List<String> list = this.topUser(user.getUserCode(), userCodes);
		Collections.reverse(list);
		TbSpScoreConfig scoreConfig = scoreConfigDao.findAllConfig().get(0);
		BigDecimal b4 = new BigDecimal(scoreConfig.getFeeRate());
		Double money = order.getAmount();
		for (int i = 0; i < list.size(); i++) {
			TbSpUser scoreUser = userDao.findByUserCode(list.get(i));
			TbSpScoreLogIn ruleInScore = channelUserScore(order, scoreUser, money, user);
			log.info("积分,,,,,,,,,,,,,,{}", ruleInScore.getReChangeScore());
			BigDecimal score = new BigDecimal(ruleInScore.getReChangeScore());
			if (Constants.TRUE.equals(ruleInScore.getStatus())) {
				scoreList.add(ruleInScore);
			}
			BigDecimal han = new BigDecimal(100);
			money = score.divide(han).doubleValue();
			log.info("用户{}对应的金额{}", scoreUser.getUserCode(), money);
			if (!scoreUser.getUserCode().equals(user.getUserCode())) {// 不是最后一级
				BigDecimal b1 = new BigDecimal(1);
				BigDecimal b2 = new BigDecimal(scoreUser.getBaseRate());
				BigDecimal b3 = new BigDecimal(money);
				// if (!scoreUser.getComCode().startsWith("WX") &&
				// !scoreUser.getComCode().startsWith("BS")) {
				// money = b3.divide(b1.subtract(b2), 6,
				// BigDecimal.ROUND_HALF_UP).multiply(b2).setScale(6,
				// BigDecimal.ROUND_HALF_UP).doubleValue();
				// log.info("传到下级的渠道佣金：{},除通道", money);
				// } else {
				// TbSpUser upScoreUser = userDao.findByUserCode(scoreUser.getComCode());
				// if (upScoreUser.getCanScore().equals(Constants.TRUE)) {
				// money = b3.divide(b1.subtract(b2), 6,
				// BigDecimal.ROUND_HALF_UP).multiply(b2).multiply(b1.add(b4))
				// .setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
				// log.info("传到下级的渠道佣金：{}", money);
				// }else {
				money = b3.divide(b1.subtract(b2), 6, BigDecimal.ROUND_HALF_UP).multiply(b2)
						.setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
				log.info("传到下级的渠道佣金：{},除通道", money);
				// }
				// }
			}
		}
		return scoreList;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Modifying(clearAutomatically = true) // @Modifying注解需要使用clearAutomatically=true，同一接口更新后立即查询获得更新后的数据,默认false查询还是更新前的数据
	public TbSpScoreLogIn channelUserScore(TbSpOrder order, TbSpUser user, Double money, TbSpUser scoreUser) {

		TbSpScoreLogIn ruleInScore = new TbSpScoreLogIn();
		TbSpScoreLogIn returnInScore = new TbSpScoreLogIn();
		TbSpScoreConfig scoreConfig = scoreConfigDao.findAllConfig().get(0);
		Double feeRate = scoreConfig.getFeeRate();
		BigDecimal b5 = new BigDecimal(feeRate);
		BigDecimal one = new BigDecimal(1);
		// 中间级
		if ((user.getComCode().startsWith("WX") || user.getComCode().startsWith("BS"))
				&& !scoreUser.getUserCode().equals(user.getUserCode())) {
			log.info("中间级：{}", user.getUserCode());
			BigDecimal base = new BigDecimal(user.getBaseRate());
			BigDecimal m = new BigDecimal(money);
			money = m.multiply(one.subtract(base)).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
		}
		// 顶级
		if (!user.getComCode().startsWith("WX") && !user.getComCode().startsWith("BS")) {
			log.info("顶级：{}", user.getUserCode());
			BigDecimal base = new BigDecimal(user.getBaseRate());
			Double rate = findRate(order, user);
			BigDecimal b1 = new BigDecimal(order.getAmount());
			BigDecimal b2 = new BigDecimal(rate);
			money = b1.multiply(b2).multiply(one.subtract(base)).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
		}
		// money=100d;
		double paramMoney = money;
		BigDecimal m2 = new BigDecimal(paramMoney);
		BigDecimal configRate = new BigDecimal(scoreConfig.getRate());
		Double score = configRate.multiply(m2).setScale(6, BigDecimal.ROUND_HALF_UP).doubleValue();
		ruleInScore.setReChangeScore(score);
		log.info("积分。。。。。。。。。。。。。。。。。。{}", score);
		// 除以通道费比例
		if (user.getComCode().startsWith("WX") || user.getComCode().startsWith("BS")) {
			TbSpUser upScoreUser = userDao.findByUserCode(user.getComCode());
			if (upScoreUser.getCanScore().equals(Constants.TRUE)) {
				BigDecimal m = new BigDecimal(money);
				money = m.divide(one.add(b5), 6, BigDecimal.ROUND_HALF_UP).setScale(6, BigDecimal.ROUND_HALF_UP)
						.doubleValue();
				log.info("渠道{}积分：{}", user.getUserCode(), money * 100);
			}
		} else {
			// 判断顶级是否送积分
			if (user.getUserType() != "3" && user.getUserType() != "4") {
				BigDecimal m = new BigDecimal(money);
				money = m.divide(one.add(b5), 6, BigDecimal.ROUND_HALF_UP).setScale(6, BigDecimal.ROUND_HALF_UP)
						.doubleValue();
				log.info("渠道{}积分：{}", user.getUserCode(), money * 100);
			}
		}

		// BigDecimal m3 = new BigDecimal(money);
		// Double inScore = configRate.multiply(m3).setScale(10,
		// BigDecimal.ROUND_HALF_UP).doubleValue();
		// log.info("积分。。。。。。。。。。。。。。。。。。{}",inScore);
		// ruleInScore.setReChangeScore(inScore);
		// 送积分
		String userCode = user.getUserCode();
		String policyNo = order.getPolicyNo();
		if (StringUtils.isBlank(user.getIdNumber())) {
			log.info("-----未实名-不获得积分-----");
			ruleInScore.setStatus(Constants.FALSE);
			return ruleInScore;
		}
		if (Constants.FALSE.equals(user.getStoreFlag())) {
			log.info("-----未开店-不获得积分-----");
			ruleInScore.setStatus(Constants.FALSE);
			return ruleInScore;
		}
		ruleInScore.setUser(user);
		List<String> changeType = Lists.newArrayList();
		changeType.add(Constants.CHANNEL_ISSUE);
		TbSpScoreLogIn dbin = scoreLogInDao.findByUCodeAndPolicyNoAndType(userCode, policyNo, changeType);
		if (null != dbin) {
			log.info("-----该保单号赠送过积分，不再赠送------{}");
			ruleInScore.setStatus(Constants.FALSE);
			return ruleInScore;
		}

		if (user.getComCode().startsWith("WX") || user.getComCode().startsWith("BS")) {
			// 首先找到其上级渠道
			TbSpUser upUser = userDao.findByUserCode(user.getComCode());
			if (Constants.TRUE.equals(upUser.getCanScore()) && money > 0) {

				returnInScore = sendScore(order, user, money, scoreUser, Constants.CHANNEL_ISSUE,
						"渠道" + (StringUtils.isEmpty(scoreUser.getUserName()) ? scoreUser.getNickName()
								: scoreUser.getUserName()) + "签单积分");
				ruleInScore.setAcChangeScore(returnInScore.getAcChangeScore());
				ruleInScore.setAccountType(returnInScore.getAccountType());
				ruleInScore.setBalance(returnInScore.getBalance());
				ruleInScore.setBranchCode(returnInScore.getBranchCode());
				ruleInScore.setChangeTime(returnInScore.getChangeTime());
				ruleInScore.setChangeType(returnInScore.getChangeType());
				ruleInScore.setEffictiveDate(returnInScore.getEffictiveDate());
				ruleInScore.setGranter(returnInScore.getGranter());
				ruleInScore.setId(returnInScore.getId());
				ruleInScore.setInvalidDate(returnInScore.getInvalidDate());
				ruleInScore.setOpenid(returnInScore.getOpenid());
				ruleInScore.setPolicyNo(returnInScore.getPolicyNo());
				ruleInScore.setReason(returnInScore.getReason());
				ruleInScore.setReasonNo(returnInScore.getReasonNo());
				ruleInScore.setRemark(returnInScore.getRemark());
				ruleInScore.setStatus(returnInScore.getStatus());
				ruleInScore.setTelephone(returnInScore.getTelephone());
				ruleInScore.setUserCode(returnInScore.getUserCode());
			} else {
				ruleInScore.setStatus(Constants.FALSE);
			}
		} else {
			// 顶级渠道
			if (!"3".equals(user.getUserType()) && !"4".equals(user.getUserType()) && money > 0) {
				returnInScore = sendScore(order, user, money, scoreUser, Constants.CHANNEL_ISSUE,
						"渠道" + (StringUtils.isEmpty(scoreUser.getUserName()) ? scoreUser.getNickName()
								: scoreUser.getUserName()) + "签单积分");
				ruleInScore.setAcChangeScore(returnInScore.getAcChangeScore());
				ruleInScore.setAccountType(returnInScore.getAccountType());
				ruleInScore.setBalance(returnInScore.getBalance());
				ruleInScore.setBranchCode(returnInScore.getBranchCode());
				ruleInScore.setChangeTime(returnInScore.getChangeTime());
				ruleInScore.setChangeType(returnInScore.getChangeType());
				ruleInScore.setEffictiveDate(returnInScore.getEffictiveDate());
				ruleInScore.setGranter(returnInScore.getGranter());
				ruleInScore.setId(returnInScore.getId());
				ruleInScore.setInvalidDate(returnInScore.getInvalidDate());
				ruleInScore.setOpenid(returnInScore.getOpenid());
				ruleInScore.setPolicyNo(returnInScore.getPolicyNo());
				ruleInScore.setReason(returnInScore.getReason());
				ruleInScore.setReasonNo(returnInScore.getReasonNo());
				ruleInScore.setRemark(returnInScore.getRemark());
				ruleInScore.setStatus(returnInScore.getStatus());
				ruleInScore.setTelephone(returnInScore.getTelephone());
				ruleInScore.setUserCode(returnInScore.getUserCode());
			} else {
				ruleInScore.setStatus(Constants.FALSE);
			}
		}
		log.info("积分。。。set。。。。。。。。。{}", score);

		return ruleInScore;
	}

	public TbSpScoreLogIn sendScore(TbSpOrder order, TbSpUser user, Double money, TbSpUser scoreUser, String changeType,
			String typeRemark) {
		TbSpScoreLogIn in = new TbSpScoreLogIn();
		try {
			log.info("===================================================================");
			TbSpScoreConfig scoreConfig = scoreConfigDao.findAllConfig().get(0);
			TbSpSaleLog saleLog = new TbSpSaleLog();
			String userCode = user.getUserCode();
			String policyNo = order.getPolicyNo();
			saleLog.setOperation(typeRemark);
			saleLog.setRequestData(userCode);
			saleLog.setUserCode(userCode);
			saleLog.setRequestTime(new Date());
			saleLog.setMark(typeRemark);
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
			String thisday = df.format(new Date());
			Date today = df.parse(thisday);
			Date startDate = order.getStartDate();
			BigDecimal configRate = new BigDecimal(scoreConfig.getRate());
			BigDecimal m = new BigDecimal(money);
			Double inScore = configRate.multiply(m).setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
			in.setChangeType(changeType);
			if (Constants.CHANNEL_ISSUE.equals(changeType)) {
				in.setAccountType(Constants.TRUE);
			} else {
				in.setAccountType(Constants.FALSE);
			}
			in.setReason(order.getProductName());
			in.setChangeTime(new Date());
			in.setStatus(Constants.TRUE);
			in.setUserCode(userCode);
			in.setPolicyNo(policyNo);
			in.setReasonNo(policyNo);
			in.setGranter("system");
			String areaCode = policyNo.substring(6, 10);
			List<TbSysHotarea> area = tbSysHotareaDao.findLikeBranchCodeLike(areaCode);
			if (CollectionUtils.isNotEmpty(area)) {
				in.setBranchCode(area.get(0).getBranchCode());
			}
			log.info("-----no cuo  7------");
			in.setEffictiveDate(order.getStartDate());
			Calendar calendar = new GregorianCalendar();
			calendar.setTime(order.getStartDate());
			calendar.add(Calendar.YEAR, scoreConfig.getPeriod());// 把日期往后增加n年.整数往后推,负数往前移动
			in.setInvalidDate(calendar.getTime());
			in.setTelephone(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
			in.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
			in.setRemark(typeRemark);
			in.setReChangeScore(inScore);// 应发
			TbSpScore newscore = null;
			List<TbSpScore> dbscore = scoreDao.findByUserCode(userCode);
			log.info("-----no cuo  8------");
			if (CollectionUtils.isNotEmpty(dbscore)) {
				log.info("-----积分送至------{}", user.getUserCode());
				newscore = dbscore.get(0);
				BigDecimal s1 = new BigDecimal(newscore.getNoeffctiveScore());
				BigDecimal s2 = new BigDecimal(inScore);
				BigDecimal s3 = new BigDecimal(newscore.getEffctiveScore());
				Double re = Math.floor(s1.add(s2).doubleValue());// 应发
				Double ac = Math.floor(s3.add(s2).doubleValue());// 实发
				if (startDate.getTime() > today.getTime()) {
					// 定时任务时确定实发
					log.info("原待生效：" + s1.doubleValue() + ",获得待生效:" + inScore + "后待生效变为" + re.doubleValue());
					saleLog.setResponseData(
							"原待生效：" + s1.doubleValue() + ",获得待生效:" + inScore + "后待生效变为" + re.doubleValue());
					in.setAcChangeScore(0.00);
					in.setBalance(0.00);
					newscore.setNoeffctiveScore(re);
				} else {
					log.info("原生效：" + s3.doubleValue() + ",获得生效:" + inScore + "后生效变为" + ac.doubleValue());
					saleLog.setResponseData(
							"原生效：" + s3.doubleValue() + ",获得生效:" + inScore + "后生效变为" + ac.doubleValue());
					in.setAcChangeScore(inScore);
					log.info("-----签单积分立即生效-----");
					if (newscore.getEffctiveScore() < 0) {// 原本积分欠额
						in.setBalance(ac > 0 ? ac : 0);
					} else {
						in.setBalance(inScore);
					}
					newscore.setEffctiveScore(ac);
				}
				newscore.setStatisticTime(new Date());
				newscore.setOpenid(StringUtils.isNotEmpty(user.getWxOpenId()) ? user.getWxOpenId() : null);
				newscore.setSumScore(Math.floor(new BigDecimal(newscore.getSumScore()).add(s2).doubleValue()));
			} else {// 新建记录
				log.info("-----no cuo  10-----}");
				newscore = new TbSpScore();
				newscore.setOpenid(StringUtils.isNotBlank(user.getWxOpenId()) ? user.getWxOpenId() : null);
				if (startDate.getTime() > today.getTime()) {
					log.info("无原待生效，加上新待生效变为：" + inScore);
					saleLog.setResponseData("无原待生效，加上新待生效变为：" + inScore);
					in.setAcChangeScore(0.00);
					in.setBalance(0.00);
					newscore.setNoeffctiveScore(inScore);
					newscore.setEffctiveScore(0.00);
				} else {
					log.info("无原生效，加上新生效变为：" + inScore);
					saleLog.setResponseData("无原生效，加上新生效变为：" + inScore);
					in.setAcChangeScore(inScore);
					in.setBalance(inScore);
					newscore.setEffctiveScore(inScore);
					newscore.setNoeffctiveScore(0.00);
				}
				newscore.setStatisticTime(new Date());
				newscore.setSumScore(inScore);
				newscore.setUserCode(userCode);
				newscore.setPhoneNo(StringUtils.isNotEmpty(user.getMobile()) ? user.getMobile() : null);
			}
			scoreLogInDao.save(in);
			scoreDao.save(newscore);
			spSaleLogDao.save(saleLog);
			log.info("------------------------------------------------------------");
			return in;
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return in;
	}

	@Override
	public TbSpUser scoreUser(TbSpOrder order) {
		TbSpUser backUser = null;
		String refereeUserCode = "";
		if (null == order) {
			log.info("-----订单为空，返回---");
			return backUser;
		}
		if (StringUtils.isBlank(order.getRefereeId())) {// 是否有推荐人
			log.info("-----规则发放没有推荐人---取当前用户---");
			if (StringUtils.isNotBlank(order.getUserId())) {
				refereeUserCode = order.getUserId();
			} else {
				log.info("-----规则发放没有推荐人、用户---");
				return backUser;
			}
		} else {
			refereeUserCode = order.getRefereeId();
		}
		TbSpUser user = userDao.findByUserCode(refereeUserCode);
		if (null == user) {
			log.info("-----找不到用户{}-不获得积分-----", refereeUserCode);
			return backUser;
		}

		backUser = user;

		return backUser;
	}

	public List<String> topUser(String userCode, List<String> upNumbers) {

		TbSpUser user = userDao.findByUserCode(userCode);
		if (null != user) {
			upNumbers.add(upNumbers.size(), user.getUserCode());
			topUser(user.getComCode(), upNumbers);
		}
		return upNumbers;
	}

	@Override
	public List<TbSpScoreLogIn> personalInScore(TbSpOrder order, TbSpUser user) {
		List<TbSpScoreLogIn> scoreList = Lists.newArrayList();
		if ("2".equals(user.getUserType()) || "5".equals(user.getUserType())) {
			TbSpUser upUser = userDao.findByUserCode(user.getComCode());
			if (null != upUser && !Constants.USER_REGISTER_TYPE_1.equals(upUser.getRegisterType())) {
				TbSpScoreConfig scoreConfig = scoreConfigDao.findAllConfig().get(0);
				BigDecimal amount = new BigDecimal(order.getAmount());
				List<String> changeType = Lists.newArrayList();
				changeType.add(Constants.DIRECT_FRIEND_ISSUE);
				TbSpScoreLogIn dbin = scoreLogInDao.findByUCodeAndPolicyNoAndType(upUser.getUserCode(),
						order.getPolicyNo(), changeType);
				if (null == dbin) {
					// 直接上级
					Double referRate = scoreConfig.getReferRate();
					if (referRate > 0) {
						log.info("直接比例大于零，直接上级送积分");
						BigDecimal referRateB = new BigDecimal(referRate);
						Double referMoney = amount.multiply(referRateB).setScale(2, BigDecimal.ROUND_HALF_UP)
								.doubleValue();
						TbSpScoreLogIn upScoreIn = sendScore(order, upUser, referMoney, user,
								Constants.DIRECT_FRIEND_ISSUE,
								"好友" + (StringUtils.isNotBlank(user.getUserName()) ? user.getUserName()
										: user.getNickName()) + "直接签单积分");
						upScoreIn.setUser(upUser);
						scoreList.add(upScoreIn);
					}
				}
				// 间接上级
				TbSpUser superUser = userDao.findByUserCode(upUser.getComCode());
				if (null != superUser && !Constants.USER_REGISTER_TYPE_1.equals(superUser.getRegisterType())) {
					List<String> supperChangeType = Lists.newArrayList();
					changeType.add(Constants.INDIRECT_FRIEND_ISSUE);
					TbSpScoreLogIn supperDbin = scoreLogInDao.findByUCodeAndPolicyNoAndType(superUser.getUserCode(),
							order.getPolicyNo(), supperChangeType);
					if (null == supperDbin) {
						Double superRateB = scoreConfig.getSuperRate();
						if (superRateB > 0) {
							log.info("间接比例大于零，间接上级送积分");
							BigDecimal superRate = new BigDecimal(superRateB);
							Double superMoney = amount.multiply(superRate).setScale(2, BigDecimal.ROUND_HALF_UP)
									.doubleValue();
							TbSpScoreLogIn scoreIn = sendScore(order, superUser, superMoney, user,
									Constants.INDIRECT_FRIEND_ISSUE,
									"好友" + (StringUtils.isNotBlank(upUser.getUserName()) ? upUser.getUserName()
											: upUser.getNickName()) + "间接签单积分");
							scoreIn.setUser(superUser);
							scoreList.add(scoreIn);
						}
					}
				}
			}
		}
		return scoreList;
	}

	@Override
	public ServiceResult findScoreConfig() {
		ServiceResult sr = new ServiceResult();
		List<TbSpScoreConfig> scoreConfigs = scoreConfigDao.findAllConfig();
		if (CollectionUtils.isNotEmpty(scoreConfigs)) {
			sr.setSuccess();
			sr.setResult(scoreConfigs.get(0));
		} else {
			sr.setAppFail("查询积分配置失败");
		}
		return sr;
	}

	public List<String> findTopBranchNo(String number, List<String> upNumbers) {
		TbSpUser user = userDao.findByUserCode(number);
		SysBranch branch = sysBranchDao.findByBranchNo(user.getComCode());
		if (null != user && null == branch) {
			upNumbers.add(user.getComCode());
			findTopBranchNo(user.getComCode(), upNumbers);
		} else if (null != user && null != branch) {
			upNumbers.add(branch.getBranchNo());
		}
		return upNumbers;
	}

	@Override
	public List<TbSpScoreLogIn> cxbInScore(TbSpOrder rewriteOrder, TbSpUser scoreUser) {
		Double referRate = null ;
		Double superRate = null ;
		List<TbSpScoreLogIn> scoreList = Lists.newArrayList();
		SysBranch branch = null ;
		
		//出单员、 业务员收益比例 按照所属二级机构配置比例结算，如果所属二级机构没有配置收益比例则按照积分管理里的积分配置结算
		if(StringUtil.isNotEmpty(scoreUser.getBranchCode())){
			branch = sysBranchDao.findByBranchNo(scoreUser.getBranchCode());
			if(null!=branch && null!=branch.getIssueRate() && null!=branch.getSaleRate()){
				referRate = branch.getIssueRate();
				superRate = branch.getSaleRate();
			}
		}else{//积分管理里的积分配置
			TbSpScoreConfig scoreConfig = scoreConfigDao.findAllConfig().get(0);
			referRate = scoreConfig.getReferRate();// 出单员收益比例
			superRate = scoreConfig.getSuperRate();// 业务员收益比例
		}
		
		Double rate = findRate(rewriteOrder, scoreUser);
		BigDecimal b1 = new BigDecimal(rewriteOrder.getAmount());
		BigDecimal b2 = new BigDecimal(rate);
		BigDecimal b3 = new BigDecimal(referRate);
		BigDecimal b4 = new BigDecimal(superRate);
		Double branchRate = 0.00;// 机构总的收益比例
		// 出单员收益
		Double money = b1.multiply(b2).multiply(b3).doubleValue();
		log.info("money{}", money);
		TbSpScoreLogIn issueer = sendScore(rewriteOrder, scoreUser, money, scoreUser, Constants.CHANGE_TYYPE_ISSUEER,
				"出单员收益");
		scoreList.add(issueer);
		// 业务员收益--是否有上级
		if (StringUtils.isNotBlank(scoreUser.getComCode())
				&& (scoreUser.getComCode().startsWith("WX") || scoreUser.getComCode().startsWith("BS"))) {
			TbSpUser upUser = userDao.findByUserCode(scoreUser.getComCode());
			Double superMoney = b1.multiply(b2).multiply(b4).doubleValue();
			log.info("superMoney{}", superMoney);
			TbSpScoreLogIn superIn = sendScore(rewriteOrder, upUser, superMoney, scoreUser,
					Constants.CHANGE_TYYPE_CLERK, "业务员收益");
			scoreList.add(superIn);
			branchRate = new BigDecimal(1).subtract(b3).subtract(b4).doubleValue();
		} else {
			branchRate = new BigDecimal(1).subtract(b3).doubleValue();
		}

		if (StringUtils.isNotBlank(scoreUser.getComCode())) {
			// 机构分红先从最上级算起
			BigDecimal b5 = new BigDecimal(branchRate);
//			List<String> userCodes = Lists.newArrayList();
//			List<String> list = findTopBranchNo(scoreUser.getUserCode(), userCodes);
//			String firstBranch = list.get(list.size() - 1);
			// List<String> branchCodes = Lists.newArrayList();
			// branchCodes.add(firstBranch);
			// List<String> allBranchs = findAllTopBranchNo(firstBranch, branchCodes);
			// for (int i = allBranchs.size() - 1; i >= 0; i--) {
			// SysBranch branch = sysBranchDao.findByBranchNo(allBranchs.get(i));
			// BigDecimal b6 = new BigDecimal(branch.getRate());
			// TbSpUser branchToUser = new TbSpUser();
			// branchToUser.setUserCode(branch.getBranchNo());
			// branchToUser.setUserName(branch.getBranchCname());
			// branchToUser.setMobile(branch.getPhoneNumber());
			// Double branchMoney = 0.00;
			// if (i==0) {//最后一级
			// if ("0000".equals(branch.getBranchNo())) {
			// branchMoney= b1.multiply(b2).multiply(b5).multiply(new
			// BigDecimal(branch.getRate())).doubleValue();
			// }else {
			// SysBranch upbranch = sysBranchDao.findByBranchNo(branch.getUpperBranchNo());
			// branchMoney= b1.multiply(b2).multiply(b5).multiply(new
			// BigDecimal(upbranch.getRate())).doubleValue();
			// }
			// }else {
			// branchMoney= b1.multiply(b2).multiply(b5).multiply(new
			// BigDecimal(1).subtract(b6)).doubleValue();
			// }
			// sendScore(rewriteOrder, branchToUser, branchMoney, scoreUser,
			// Constants.CHANGE_TYYPE_BRANCH, "机构收益");
			// }

			// 只送总公司
//			SysBranch branch = sysBranchDao.findByBranchNo("0000");
			// BigDecimal b6 = new BigDecimal(branch.getRate());
			if(null!=branch){
				TbSpUser branchToUser = new TbSpUser();
				branchToUser.setUserCode(branch.getBranchNo());
				branchToUser.setUserName(branch.getBranchCname());
				branchToUser.setMobile(branch.getPhoneNumber());
				Double branchMoney = 0.00;
				branchMoney = b1.multiply(b2).multiply(b5).doubleValue();
				sendScore(rewriteOrder, branchToUser, branchMoney, scoreUser, Constants.CHANGE_TYYPE_BRANCH, "机构收益");
			}
		}
		return scoreList;
	}

	public List<String> findAllTopBranchNo(String number, List<String> upNumbers) {
		SysBranch branch = sysBranchDao.findByBranchNo(number);
		if (null != branch && !branch.getBranchNo().equals("00000000")) {
			upNumbers.add(branch.getUpperBranchNo());
			findAllTopBranchNo(branch.getUpperBranchNo(), upNumbers);
		}
		return upNumbers;
	}
}
